在我的数据库中,有一个名为SetVoca
的集合,其结构如下:
{
"_id" : ObjectId("5e63518c3e5d0d08980e2203"),
"lessonId" : "5e63518c3e5d0d08980e2201",
"vocaList" : [
{
"_id" : ObjectId("5e6351e43e5d0d08980e2207"),
"word" : "a",
"type" : "a",
"meaning" : "a",
"sente" : "a",
"semean" : "a",
"sug" : "a"
},
{
"_id" : ObjectId("5e6351eb3e5d0d08980e2208"),
"word" : "b",
"type" : "b",
"meaning" : "b",
"sente" : "b",
"semean" : "b",
"sug" : "b"
}
],
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5e6351be3e5d0d08980e2206"),
"lessonId" : "5e6351be3e5d0d08980e2204",
"vocaList" : [
{
"_id" : ObjectId("5e6351f63e5d0d08980e2209"),
"word" : "c",
"type" : "c",
"meaning" : "c",
"sente" : "c",
"semean" : "c",
"sug" : "c"
}
],
"__v" : 0
}
现在,我将 vocaList 字段中的 ObjectId 值分散到一个数组中,如下所示:
const vocaIds = ['5e6351e43e5d0d08980e2207', '5e6351eb3e5d0d08980e2208', '5e6351f63e5d0d08980e2209']
现在我想根据我保存在 vocaIds
数组中的 Id 检索分散在 vocaList
字段中的对象。我尝试像这样编写代码:
app.get('/saved-find', (req, res) => {
SetVoca.find({ 'vocaList': { '_id': { $in: vocaIds } } }, (err, result) => {
console.log(result);
});
});
不幸的是它不起作用,所以我应该修复它才能运行它。非常感谢。
最佳答案
您需要将您的 id 包装在 ObjectId 中来发送,如下所示
const vocaIds = [mongoose.Types.ObjectId('5e6351e43e5d0d08980e2207'), mongoose.Types.ObjectId('5e6351eb3e5d0d08980e2208'), mongoose.Types.ObjectId('5e6351f63e5d0d08980e2209')]
在查询中这样做
SetVoca.find({ 'vocaList._id': { $in: vocaIds } }, (err, result) => {
console.log(result);
});
关于javascript - 如何根据Js数组中保存的Id获取分散在数组字段中的Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578194/