简体   繁体   English

mongoose 如何从对象数组中的属性中查找

[英]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. obj1 到 objn 具有相同的结构和字段。

I want to query a Model with mongoose, to find docs that has equal value to "field1" in that list of objects "listOfObjects".我想查询 Model 和 mongoose,以在该对象列表“listOfObjects”中查找与“field1”具有相同值的文档。

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.您需要使用 Javascript 的过滤器方法来执行此操作。

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.使用直接查询从 mongoDb 本身中过滤掉这些对象。 This is more efficient than retrieving all the mongoDb documents and then using a Javascript filter.这比检索所有 mongoDb 文档然后使用 Javascript 过滤器更有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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