10

I'm shortlisting the 2 elements from one schema and want to update in another schema. for that i used slice method to shortlist first 2 elements from an array. but am Getting

CoreMongooseArray ['element1','element2']

instead of ["element1", "element2"]

How do i remove "CoreMongooseArray" ?

connection.connectedusers.find({},  async (err, docs) => {
if(err) throw err;
var users = docs[0].connectArray;
if (docs[0] != null && users.length >= 2) {
 var shortListed = users.slice(0, 2);
 try {
                await connection.chatschema.updateMany({}, { $push: { usersConnected: [shortListed] } }, { upsert: true });
            } catch (err) {
                res.status(201).json(err);
            }
}
vinaykumar0459
  • 497
  • 1
  • 6
  • 19

4 Answers4

20

You need to add lean() to your query.

From the docs:

Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters, virtuals, or other Mongoose features.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
12

If you already got the mongoose array and like to convert to simple js array

const jsArray = mongooseArray.toObject();

https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-toObject

dang
  • 1,549
  • 1
  • 20
  • 25
1

For some reason .toObject() didn't work for me. lean() option works, but it's not suitable when you already have an object with mongoose array in it. So in case if you already have mongoose array and you want just to convert it to plain js array you can use following code:

function mongooseArrayToArray(mongooseArray) {
  const array = [];
  for (let i = 0; i < mongooseArray.length; i += 1) {
    array.push(mongooseArray[0]);
  }
  return array;
};

usage:

const array = mongooseArrayToArray(mongooseArray);
IliaEremin
  • 3,338
  • 3
  • 26
  • 35
1

If you just want to convert the CoreMongooseArray to a normal array without changing anything else:

const jsArray = [...mongooseArray];
stephan
  • 655
  • 1
  • 7
  • 11