【问题标题】:Mongoose array of objects query by slug通过 slug 查询对象的 Mongoose 数组
【发布时间】:2017-03-27 15:30:00
【问题描述】:

我正在尝试查询具有此类对象数组的文档。它是添加标签的历史记录。

{
    "added_by" : ObjectId("58d92d8b11af264b87a8f5d4"),
    "tag" : ObjectId("58d92d8b11af264b87a8f5ed"),
    "_id" : ObjectId("58d92d8c11af264b87a8f6d5"),
    "added_at" : ISODate("2017-03-02T22:06:42.788Z")
}

我无法仅对 _id 进行查询

我试过这个:

var query = {
    'tags.tag': {
        slug: $in: ['tag-name']
    }
}
Node.find(query, (err, nodes) => {
    if (err) {
        res.status(404)
        res.send(err)
    } else {
        res.json(nodes);
    }
}).populate(['tags.tag'])

这是文件:

{
    "_id" : ObjectId("58d92d8c11af264b87a8f6d0"),
    "user_id" : ObjectId("58d92d8b11af264b87a8f5d4"),
    "uid" : "-KeG2FvL0jwkHFvOautH",
    "updated_at" : ISODate("2017-03-02T22:06:42.788Z"),
    "created_at" : ISODate("2017-03-02T22:06:42.051Z"),
    "tags" : [ 
        {
            "added_by" : ObjectId("58d92d8b11af264b87a8f5d4"),
            "tag" : ObjectId("58d92d8b11af264b87a8f5ed"),
            "_id" : ObjectId("58d92d8c11af264b87a8f6d5"),
            "added_at" : ISODate("2017-03-02T22:06:42.788Z")
        }, 
        {
            "added_by" : ObjectId("58d92d8b11af264b87a8f5d4"),
            "tag" : ObjectId("58d92d8b11af264b87a8f626"),
            "_id" : ObjectId("58d92d8c11af264b87a8f6d4"),
            "added_at" : ISODate("2017-03-02T22:06:42.788Z")
        }
    ],
    "status" : "publish",
    "description" : "some text here",
    "title" : "Anna James",
    "__v" : 0
}

有什么想法吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    由于你存储了对标签的引用,所以你需要先通过slug来获取标签:

    TagsCollection.find({slug:'tag-name'}, (err, tags)...)
    

    然后按tag._id过滤:

    var query = {
        'tags.tag': new ObjectId(tag._id)
    }
    

    var query = {
        'tags.tag': {'$in": [new ObjectId(tag._id), ....]}
    }
    

    如果你有超过 1 个标签匹配 slug。

    老实说,如果将标签直接存储在文档中,而不是存储引用,效率会更高。

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2014-05-13
      • 2022-11-11
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多