Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreMongooseArray to Normal Array

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);
            }
}
like image 834
vinaykumar0459 Avatar asked Jun 19 '19 12:06

vinaykumar0459


3 Answers

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.

like image 137
Tom Slabbaert Avatar answered Oct 20 '22 04:10

Tom Slabbaert


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

like image 11
dang Avatar answered Oct 20 '22 05:10

dang


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);
like image 1
IlyaEremin Avatar answered Oct 20 '22 04:10

IlyaEremin