【问题标题】:Translate MongoDB shell query to js将 MongoDB shell 查询转换为 js
【发布时间】:2021-03-17 20:01:19
【问题描述】:

我在将 MongoDB shell 查询重写为 JavaScript 时遇到问题。

这是一个有效的 shell 查询(它返回预期的对象):

db.decks.aggregate([
    {$match: {_id: ObjectId('605072934f19160027b0c1a9')}},
    {
        $lookup: {
            "from": "cards",
            "localField": "cards",
            "foreignField": "_id",
            "as": "cards"
        }
    }
])

现在我尝试在我的 JS 代码中这样写:

const deck = await Deck.aggregate([
            {$match: {"_id": `ObjectId(${id})`}},
            {
                $lookup: {
                    "from": "cards",
                    "localField": "cards",
                    "foreignField": "_id",
                    "as": "cards"
                }
            }
        ])

$match 不匹配任何内容。我尝试了各种不同的引号。有和没有ObjectId。我看不出这里有什么问题。 Deck 是合适的模型(await Deck.findById(id) 工作正常)。

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

好吧,您正在对ObjectId 函数进行字符串化。 试试这个:

const mongo = require('mongodb');

const itemID = <item id>;

const deck = await Deck.aggregate([
    {
        $match: { "_id": new mongo.ObjectID(itemID) }
    },
    {
        $lookup: {
            "from": "cards",
            "localField": "cards",
            "foreignField": "_id",
            "as": "cards"
        }
    }
]);

【讨论】:

  • 感谢您的回复。您对 ObjectID 的 stringify 是正确的。 new mongo.Types.ObjectId(id) 是正确答案。
猜你喜欢
  • 1970-01-01
  • 2018-08-28
  • 2020-01-19
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
相关资源
最近更新 更多