Home > Blockchain >  mongoose how to find from a property in an array of objects
mongoose how to find from a property in an array of objects

Time:09-15

I have an array of objects with these fields :

let obj1 : {field1 : value1,  field2 : value2, field3 : value3};

let listOfObjects : [obj1 , obj2 , obj3 , obj4 .... objn]

obj1 till objn have the same structure and fields.

I want to query a Model with mongoose, to find docs that has equal value to "field1" in that list of objects "listOfObjects".

I have tried this and it worked, but looking for a better solution if it is possible.

let valuesList = listOfObjects.map( x => x.field1);
let docs = await Model.find({keyToFind : valuesList});

thanks in advance

CodePudding user response:

You need to use Javascript's filter method to do so.

Here is the code snippet / solution:

let listOfObjects = [ 
  {field1 : 'value1',  field2 : 'value2', field3 : 'value3'}, 
  {field1 : 'value12',  field2 : 'value21', field3 : 'value31'}, 
  {field1 : 'value13',  field2 : 'value22', field3 : 'value32'}, 
  {field1 : 'value14',  field2 : 'value23', field3 : 'value33'}, 
  {field1 : 'value1',  field2 : 'value24', field3 : 'value34'}
];

console.log(`List of objects: `, listOfObjects)

let vList = listOfObjects.filter(x => listOfObjects[0].field1 === x.field1)

console.log(`Here is the Expected Solution:`); 

// field1 of first object matches with the field1 of last object in the list of objects. So, two objects are returned in the result.

console.log(vList)

CodePudding user response:

Use a direct query to filter out these objects from mongoDb itself. This is more efficient than retrieving all the mongoDb documents and then using a Javascript filter.

let docs = await Model.find({'ModelName.field1' : value1});

  • Related