通过_id在mongodb数据库中的对象数组中查找

时间:2018-01-08 04:20:46

标签: mongodb mongoose mongoose-schema

我正在尝试在对象数组中找到对象的id。该_id与文档中的其他字段具有相同的字段名称_id。 这是我的模型(简要)

_id: ObjectId(5a52540638086448bf4235e8)
beName: Name1
beLink: Link1
cards: Array
 0: Object
    cardType: type1
    cardBundle: 1
    _id: ObjectId(5a526749d0ddab4bcdcc1556)
 1: Object
    cardType: type2
    cardBundle: 1
    _id: ObjectId(5a526749d0ddab4bcdcc1557)

...

_id: ObjectId(5a52540638086448bf4235e9)
beName: Namex
beLink: Linkx
cards: Array
 0: Object
    cardType: typex
    cardBundle: x
    _id: ObjectId(5a526749d0ddab4bcdcc1598)
 1: Object
    cardType: type2
    cardBundle: 1
    _id: ObjectId(5a526749d0ddab4bcdcc1599)

这是我的数据库内容的示例

Cards.find({ _id: req.params.id}, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });

我正在尝试找到像这样的特定卡片的ID

Cards.find({ _id: new ObjectId(req.params.id)}...

但我得到一个空的结果

我也试过

caniuse

3 个答案:

答案 0 :(得分:1)

您可能需要使用aggregate功能$unwind卡片组来查找基于_id的匹配卡片。

所以,在mongoose而不是find使用aggregate管道

示例文档

> db.cards.findOne()
{
    "_id" : ObjectId("5a52f4136fe82b42b7439a21"),
    "beName" : "Name1",
    "beLink" : "Link1",
    "cards" : [
        {
            "cardType" : "type1",
            "cardBundle" : 1,
            "_id" : "5a52f3a66f112b42b7439a20"
        },
        {
            "cardType" : "type2",
            "cardBundle" : 1,
            "_id" : "5a52f3a66f112b42b7439a21"
        }
    ]
}

聚合函数

> db.cards.aggregate([{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] )

结果文档

> db.cards.aggregate([{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] ).pretty()
{
    "_id" : ObjectId("5a52f4136fe82b42b7439a21"),
    "beName" : "Name1",
    "beLink" : "Link1",
    "cards" : {
        "cardType" : "type1",
        "cardBundle" : 1,
        "_id" : "5a52f3a66f112b42b7439a20"
    }
}
> 

如果您知道父_id,在父汇$match的汇总管道_id,然后是$unwind,然后$match,您可以进一步优化它阵列卡_id

> db.cards.aggregate([{$match:{"_id":ObjectId("5a52f4136fe82b42b7439a21")}},{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] )

答案 1 :(得分:1)

问题有点含糊,但通过查看其他答案并在 url 中包含卡片的 _id,我猜您有卡片的 _id 并且您想找到父文档。如果为真,则您不需要聚合。一个查找查询就可以完成这项工作:

db.cards.find({"cards._id": _id})

答案 2 :(得分:0)

尝试这样做:

const ObjectId = require("mongodb").ObjectID,

/* some other statements */

let cardId = new ObjectId(req.params.id)
Cards.find({ _id: cardId}, function (err, post) {
    if (err) return next(err);
    res.json(post);
});

供参考:https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html