简体   繁体   中英

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

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

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)

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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM