javascript - 如何根据Js数组中保存的Id获取分散在数组字段中的Object

标签 javascript node.js mongodb mongoose

在我的数据库中,有一个名为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/

相关文章:

javascript - 文档就绪触发,但其附加功能不触发

php - 如何在设置前一个列表框值时设置选择框或下拉列表框的值

javascript - HTTP 错误 307 - Node.js (Express)、passport.js、mongoose.js 和 Android 应用程序中的临时重定向

json - Mongo-go-driver 从插入结果中获取 objectID

javascript - 如何将 <span> 或 <div> 标签内容显示为星号 (*)

javascript - Mongoose/MongoDB - 如何在聚合查询中使用 promise

node.js - 如何阅读使用 Node 在Firestore中创建的最新文档?

node.js - 将文件上传到本地目录以及 MongoDB

php - MongoDB/DocumentDB bson_append_array() : invalid array detected. 数组参数的第一个元素不是 "0"

mongodb - 如何创建 mongodb 包以在 Ubuntu 上使用 apt-get 安装?