[英]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.