简体   繁体   English

如何在猫鼬中查询对象数组内的值

[英]how to query value inside of object array in mongoose

I'm trying to get document that it's 'from' field value in 'from' of 'periods' array. 我正在尝试获取文档,该文档是'periods'数组的'from'中的'from'字段值。

I've tried followings but it doesn't work. 我试过以下方法,但不起作用。 how can i? 我怎样才能?

periods = [{
    from: 333,
    to: 555
},
{
    from: 666,
    to: 777
}]

var eqbookschema = new Schema({
eq_dbId: String,
user_dbId: String,
from: Number,
to: Number,
timestamp: Number,
}, {collection: 'book'});

EQBook = mongoose.model('EQBook', eqbookschema)

EQBook.find({
    eq_dbId: req.body.eq_dbId,
    from: {$in: [periods.from]}
})

The query I have tried only returns empty array although existing. 我尝试过的查询虽然存在,但只会返回空数组。

Because periods is an array of object and you want to find based on from field of each element so you need to map it first: 由于periods是一个对象数组,因此您要根据每个元素的from字段进行查找,因此需要首先对其进行映射:

let froms = periods.map(val => val.from);

Then find with mapped array: 然后用映射数组查找:

EQBook.find({
  eq_dbId: req.body.eq_dbId,
  from: {$in: froms}
})

Or just: 要不就:

EQBook.find({
  eq_dbId: req.body.eq_dbId,
  from: {$in: periods.map(val => val.from)}
})

create an array of 'from' values only 仅创建一个'from'值的数组

periodFrom = periods.map((elem)=>elem.from);

EQBook.find(
  {eq_dbId: req.body.eq_dbId,from:{$in:periodFrom}}
)

You can try this. 你可以试试看

const ObjectId = require('mongodb').ObjectId;
let froms = periods.map(data => data.from);
EQBook.aggregate([
{
 $match : {'eq_dbId': ObjectId(req.body.eq_dbId),'from':{$in:[periodFrom]}
}
])

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

相关问题 如何通过 mongoose(javascript)中的多个值查询数组内的 object? - How to query an object inside an array by multiple value in mongoose (javascript)? 如何使用 mongoose 查询嵌套 object 内的数组? - How to query array inside nested object using mongoose? 如何在 mongoose 的查询中写入查询值 - How to write query value inside of query of mongoose 如何在 mongoose 的数组中返回匹配的 object - How to return a matched object inside an array in mongoose 如何在猫鼬的对象数组中搜索对象? - how to search an object inside an array of objects in mongoose? 如何在 mongoose model 的数组内部更改 object 内部的单个值并保存? - How to change a single value inside of an object inside of an array in a mongoose model and save it? 如何将元素推入 Mongoose 中另一个数组中的 object 中的数组? - How to push an element into an array inside an object inside another array in Mongoose? 猫鼬,如何查询对象数组中的最大值或最小值并返回对象 - mongoose, how to query the maximum or minimum value in the a object-array and return the object 如何从猫鼬中的多个数组更新数组中的值? - How to update value inside an array from multiple array in Mongoose? 如果用户在用户数组中,如何使用 mongoose 查询查找 - how to find using mongoose query if user is inside an array of users
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM