Type is missing the following properties from type ‘Schema<any, Model, {}, {}>’: add, childSchemas, clearIndexes, clone, and 37 more

I’ve got a Mongoose on TypeScript, and it worked without interfaces and types defining, but when I decided to define types, the madness started. I’ve watched tons of manuals and topics and found nobody with a similar problem. I tried to define a model strictly by the manual, but I’m getting an error. Here’s my model file:

import mongoose from 'mongoose';
import { nanoid } from 'nanoid';

const GeoSchema = new mongoose.Schema({
    type: {
        type: String,
        default: 'Point',
        enum: ['Point'],
    },
    coordinates: {
        type: [Number, Number],
        index: '2dsphere',
    },
});

interface postInterface extends mongoose.Document {
    shortId: string;
    createdBy: string;
    title: string;
    description: string;
    tags: string[];
    location: {};
    images: string[];
    contacts: {
        email: Boolean;
        wa: Boolean;
        phone: Boolean;
    };
    type: 'available' | 'wanted';
    is_moderated: Boolean;
}

export const PostSchema = new mongoose.Schema(
    {
        shortId: {
            type: String,
            index: true,
            default: () => nanoid(),
        },
        createdBy: {
            type: String,
            index: true,
        },
        title: String,
        description: String,
        tags: [String],
        location: GeoSchema,
        images: [String],
        contacts: {
            email: Boolean,
            wa: Boolean,
            phone: Boolean,
        },
        type: { type: String, enum: ['available', 'wanted'] },
        is_moderated: Boolean,
    },
    { timestamps: true }
);

export const Post = mongoose.model<postInterface>('Post', PostSchema);

When I import it into another file, on the line

return Post.create(post)

the linter gives me the error:

Type 'postInterface & { _id: any; }' is missing the following properties from type 'Schema<any, Model<any, any, any, any>, {}, {}>': add, childSchemas, clearIndexes, clone, and 37 more.ts(2740)

I googled examples of typescript model defining, and it looks like something that works for others doesn’t work for me.

What am I doing wrong?

I can’t replace the value of an array returned by mongoose

I have a notifications.find query (mongoose) that returns multiple sheets

Notification.find({id: id}, function(err, notifications){}

I need to convert the timestamp values that are returned like that

[                                                                                             
  {
    _id: new ObjectId("12934193c51a231b0165425a"),
    userid: '62921df1c14a2eea0efa9399',
    timestamp: 1653817696599,
  },
  {
    _id: new ObjectId("11934193c51a231b0165425a"),
    userid: '62921df1c14a2eea0efa9399',
    timestamp: 1653817696600,
  }
]

I tried this

notifications.forEach((element, index) => {

notifications[index].timestamp = new Date(notifications[index].timestamp);

});

and this code

new Date(notifications[index].timestamp);

seems to work by converting the timestamp of each value, but I can’t replace it in the array

I’ve been on this issue for several hours

send multiple ajax post requests at regular intervals until any one of them passed

I am writing a test program for website most of time the website gives 504 error.
i want to write a program that can sent ajax requests to server and replace page with server response html.
the process of requests is like :

  1. send 20 requests at a time if any of them got 200 response then cancell
    all other requests
  2. repeat step 1 after 10 seconds until any request got valid response.

currently i am making 20 ajax calls and the wait for any of them to complete using Promise.any().
the problem i am facing is that how can i manage all batches in one Promise.any() because i need to keep track of previous batch as well like if one of second batch calls completed i need to cancell all first batch calls and remaining 2nd batch calls.
Hope you got my point what i want.
here is the code i have done so far

var reqs = [];
async function post_page(url, i){

    var formElement = document.getElementById('form1');
    var data = new URLSearchParams(new FormData(formElement));
    data.append('continue', 'Continue');

    let controller = new AbortController();
    var req = fetch(url, {
        method: 'post',
        body: data,
    }
     ).then(response => {
      if (!response.ok) {
            return Promise.reject('not ok');
        }
      return (response, i);
  });
    reqs.push(controller);
};

var load_page = function(url){
    var promises = [];

    for(var i = 0 ; i < 10; i++){
        promises.push(post_page(url, i));
    };

     Promise.any(promises).then((value, index) => {
         reqs.splice(index,1);
         $.each(reqs, function(id, req){req.abort();})
        loadPageHtml(value);
    })
};

Why is withAuthenticator() not working React Native?

So, I have deployed an AWS Amplify Project and I have completed the staging steps. I wanted to use the withAuthenticator() to display the default Auth flow provided by AWS. I am unable to do so even after the documentation provided by the AWS website.

Code is given below-

import React from 'react';
import {SafeAreaView, StyleSheet} from 'react-native';

import {withAuthenticator} from 'aws-amplify-react-native';
import {Amplify} from 'aws-amplify';
import awsconfig from './src/aws-exports'; 

Amplify.configure(awsconfig);

import Navigation from './src/navigation';
const App = () => {
  return (
    <SafeAreaView style={styles.root}>
      <Navigation />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  root: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

export default withAuthenticator(App);

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading ‘hash’)

I am trying to make a solution to store the file in IPFS , and then put the hash on the blockchain.
But when I try to upload the file to IPFS here comes the error message

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading ‘hash’)

I am using react , ganache , node.js , ipfs-http-client
here’s my app.js code

import React, {Component} from 'react'
import SimpleStorageContract from '../src/SimpleStorage.json'
import getWeb3 from './utils/getWeb3'
import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'
const ipfsAPI = require('ipfs-http-client');
const ipfs = ipfsAPI.create({host: 'localhost', port: '5001', protocol: 'http'});
const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
let account;
// Declaring this for later so we can chain functions on SimpleStorage.
let contractInstance;
let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      resolve(response[0].hash);
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}


class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      blockChainHash: null,
      web3: null,
      address: null,
      imgHash: null,
      isWriteSuccess: false
    }
  }
  componentWillMount() {
    ipfs.swarm.peers(function(err, res) {
      if (err) {
        console.error(err);
      } else {
        // var numPeers = res.Peers === null ? 0 : res.Peers.length;
        // console.log("IPFS - connected to " + numPeers + " peers");
        console.log(res);
      }
    });
    getWeb3.then(results => {
      this.setState({web3: results.web3})
      // Instantiate contract once web3 provided.
      this.instantiateContract()
    }).catch(() => {
      console.log('Error finding web3.')
    })
  }
  instantiateContract = () => {
    simpleStorage.setProvider(this.state.web3.currentProvider);
    this.state.web3.eth.getAccounts((error, accounts) => {
      account = accounts[0];
      simpleStorage.at('0xe7D98C99d71438A072B020138dD75347792FA214').then((contract) => {
        console.log(contract.address);
        contractInstance = contract;
        this.setState({address: contractInstance.address});
        return;
      });
    })
  }
  render() {
    return (<div className="App">
      {
        this.state.address
          ? <h1>CONNECT THE CONTRACT ADDRESS:{this.state.address}</h1>
          : <div/>
      }
      <h2>UPLOAD TO IPFS:</h2>
      <div>
        <label id="file">CLICK TO UPLOAD THE FILE</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = function(e) {
              console.log(reader);
              saveImageOnIpfs(reader).then((hash) => {
                console.log(hash);
                this.setState({imgHash: hash})
              });
            }.bind(this);
          }}>UPLOAD TO IPFS AND RETURN THE HASH</button>
      </div>
      {
        this.state.imgHash
          ? <div>
              <h2>imgHash:{this.state.imgHash}</h2>
              <button onClick={() => {
                  contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                    console.log('HASH HAS BEEN WRITE ON BLOCKCHAIN');
                    this.setState({isWriteSuccess: true});
                  })
                }}>PUT HASH ON BLOCKCHAIN:contractInstance.set(imgHash)</button>
            </div>
          : <div/>
      }
      {
        this.state.isWriteSuccess
          ? <div>
              <h1>HASH IS ON THE BLOCK CHAIN</h1>
              <button onClick={() => {
                  contractInstance.get({from: account}).then((data) => {
                    console.log(data);
                    this.setState({blockChainHash: data});
                  })
                }}>READ HASH ON BLOCKCHAIN:contractInstance.get()</button>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h3>READ THE HASH ON BLOCKCHAIN:{this.state.blockChainHash}</h3>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h2>BROWSER ACCESS:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
              <img alt="" style={{
                  width: 1600
                }} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}
export default App

i hope someone can be my savior , thank you really much.

stopPropagation in the filter sidebar of Shopware 6 does not allow nested collapsibles

The Shopware 6 sidebar has bootstrap collapsible items for the filters. As we have a lot of filter options for one property, we put them in a properties / sub-property structure and want to collapse the child items.

So we added

<span class="collapsed" aria-expanded="false" data-toggle="collapse" data-target="#element-2647292d65d44853b2b3faaaf5a9572e">
    <span class="icon icon-arrow-medium-down icon-xs">
                    <svg> [ chevron icon ] </svg>
    </span>
</span>

And have put the subitems in a div:

<div class="subelement-group collapse" id="element-2647292d65d44853b2b3faaaf5a9572e">

It is not working, and after some debugging we found, that there is an additional event listener attached to the span which should expand the subitems div.

The attached event is this:

dropdownMenu.addEventListener('click', (event) => {
   event.stopPropagation();
});

If we remove the stopProgation call, everything seems to work fine.
Now we a wondering if we just just make a pull request for the Shopware core which removes this line or what could be the reason why it was added.

We also believe that there is no other way to undo the stop propagation?

Workaround – Safari does not respect the hidden attribute on select > option elements

I was developing an HTML form and realised that the behaviour of the select field was quite different on iOS Safari to other browsers (including several android based browsers).

Safari mobile was ignoring the hidden attribute of my option elements, allowing the user to select placeholder values. While it’s possible to set the disabled attribute which prevents the user from selecting them on iOS, this still shows those fields to the user, and it has to be handled with media queries as then the option elements are not shown at all (even as placeholders) in other browsers.

I wanted a seamless universal solution. A bit of reading and experimentation indicated that Safari was actually stripping the hidden attribute and generating a popover from the options.

Of course, if the option tag isn’t there, it can’t generate a popover containing them…

How to fix the javascript execution error in blogger

<script>
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
  this.classList.toggle("active");
  var content = this.nextElementSibling;
  if (content.style.maxHeight){
    content.style.maxHeight = null;
  } else {
    content.style.maxHeight = content.scrollHeight + "px";
  } 
});
}
</script>

When I am using this code in blogger this shows:-

“org.xml.sax.SAXParseException; lineNumber: 301; columnNumber: 16; The content of elements must consist of well-formed character data or markup.
“

Here is the image

Please help me how to fix this problem

spreading an array returned from an async function results in empty array? [duplicate]

I am attempting set a constant to an array of objects which is returned from an async function. When I log the constant, the result is as expected:

code:

const songList = songsArrayFromIdList(rehearsal.rehearsallist);
console.log(songList);

logs (as expected):

[]
0: {formtake: 'https://...
1: {userpracticed: 'do...
2: {formtake: 'https://yo...
3: {titleabbreviation: 'DPM', formtake: 'https...
length: 4
[[Prototype]]: Array(0)

However, I’d like to spread the returned array of objects into the constant in order to in create a new array reference (to later include in a React state object). But, when I spread the returned array into the constant it logs an empty array:

const songList = [...songsArrayFromIdList(rehearsal.rehearsallist)];
console.log(songList);

logs (unexpectedly):

[]
length: 0
[[Prototype]]: Array(0)

very frustrated. I feel like the obvious issue has something to do with the array returning from an async function. But, clearly the array is usable due it logging properly when not spread??

What am I missing?

Thanks in advance.

convert byte array to C-Style WORD, DWORD adn String in javascript

Having to deal with many file header format i.e. bmp, tiff, wav, mp3, etc…
I developed a few basic routines to deal with them.
I was wondering if there was a better way?
Also they do not deal with signed nor float value.

  function Read2BytesToUWord   (ThisArray, Offset, UseLittleEndian){

    let ThisWord              = 0;

    if(UseLittleEndian){
      ThisWord               |= ThisArray[Offset + 1].charCodeAt() << 8;
      ThisWord               |= ThisArray[Offset + 0].charCodeAt();
    } else {
      ThisWord                = ThisArray[Offset + 0].charCodeAt();
      ThisWord               |= ThisArray[Offset + 1].charCodeAt() << 8;
    }
    return Number((ThisWord));
  }
  function Read4BytesToUDWord   (ThisArray, Offset, UseLittleEndian){

    let ThisDWord             = 0;

    if(UseLittleEndian){
      ThisDWord               = ThisArray[Offset + 3].charCodeAt() << 24;
      ThisDWord              |= ThisArray[Offset + 2].charCodeAt() << 16;
      ThisDWord              |= ThisArray[Offset + 1].charCodeAt() << 8;
      ThisDWord              |= ThisArray[Offset + 0].charCodeAt();
    } else {
      ThisDWord               = ThisArray[Offset + 3].charCodeAt();
      ThisDWord              |= ThisArray[Offset + 2].charCodeAt() << 8;
      ThisDWord              |= ThisArray[Offset + 1].charCodeAt() << 16;
      ThisDWord              |= ThisArray[Offset + 0].charCodeAt() << 24;
    }
    return Number((ThisDWord));
  }
  function ReadBytesToString    (ThisArray, Offset, ThisLen){
    let ThisStr  = "";
    for(let Indx = 0; Indx < ThisLen; Indx++){
      ThisStr   += (ThisArray[Offset + Indx]); 
    }
    return ThisStr;
  }

Why mongoose.model() is required to get data from MongoDB?

I want to read data from the mongodb with mongoose, but every time it requires creating a model. Why?
I thought model are just like templates to insert data to MongoDB.
Can anyone describe what exactly mongoose.model() is and how it works?

I tried

const Model = mongoose.model(mongoose.Schima())

Without object in it
And it worked as well!!!

Thank you…

How do I tell if my player is to the left or the right of my enemy in javascript?

I need to check if my player is on the left side or the right side of my enemy sprite so that I can move the enemy toward the player in that direction.

How do you check what side a sprite is on relative to another sprite?

I am using Kaboom.js, Javascript, on Replit.com


export default function run(speed = 250) {
    return {
        id: "run",
        require: [ "pos", "area", ],
        add() {
            if (   player is on left of enemy   ) {
                this.move(LEFT, speed)
            } else if (   player is on right of enemy   ) {
                this.move(RIGHT, speed)
            }
        },
    }
}

How do you change the background colour on scroll?

I’m trying to change the background colour of my webpage on scroll using IntersectionObserver- this is the code I have so far:

const callback = (entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        style.backgroundColor = entry.target.getAttribute('data-color');
      }
    });
  };
  
  const changes = document.querySelectorAll('.change');

  const observer = new IntersectionObserver(callback);

  changes.forEach(change => {
    observer.observe(change);
});

I would like to have it change colour when the viewer scrolls to a div, possibly using something like

<div id= "indiaText" class="change" data-color="orange">

Does anyone have an idea of how I can achieve this? I have also tried $(window).scroll(function() { however I only get an error using this method. Thank you

How to get data properly using axios and Redux?

I am displaying all information without problems but when try to display image it shows nothing shows error either.

Trying to parse price before return it const priceFloat = (product.price).toFixed(2); shows i am trying to Cannot read properties of undefined (reading 'toFixed') and inspecting Redux status product is empty, trying to print console.log(product?.images[0].url); also get same error but lines above i get product.ratings for starsOptions without problems. Its kind of confusing for me.

Whatever on return to display item.url it shows nothing but inspecting Redux i see all information (image)

import Carousel from "react-material-ui-carousel";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";

export const ProductDetails = () => {
  const { id } = useParams();
  const dispatch = useDispatch();
  const alert = useAlert();
  const { product, loading, error } = useSelector(
    (state) => state.productDetails
  );
  useEffect(() => {
    if (error) {
      alert.error(error);
      dispatch(clearErrors());
    }
    dispatch(getProductDetails(id));
  }, [dispatch, id, error, alert]);

  const starsOptions = {
    edit: false,
    color: "rgba(20,20,20,0.1)",
    activeColor: "#FAC213",
    size: window.innerWidth < 600 ? 20 : 25,
    value: product.ratings,
    isHalf: true,
  };
  //const priceFloat = (product.price).toFixed(2);
  let reviewText;
  product.numOfReviews == 1
    ? (reviewText = "Reseña")
    : (reviewText = "Reseñas");
  //console.log(product?.images[0].url);
  return (
    <>
      {loading ? (
        <Loader />
      ) : (
        <>
          <div className="ProductDetails">
            <div>
              <Carousel>
                {product.images &&
                  product?.images.map((item, i) => {
                    <img
                      className="CarouselImage"
                      key={item.public_id}
                      src={item.url}
                      alt={`${i} Slide`}
                    />;
                  })}
              </Carousel>
            </div>

Redux status