Mongoose在对象数组值中查找

时间:2014-02-28 21:17:47

标签: javascript node.js mongodb mongoose

文章对象数组的示例:

[
    {
        "_id": "72",
        "title": "Some title",
        "comments": [
            {
                "title": "title 1",
                "_id": "0",
            },
            {
                "title": "title 2",
                "_id": "1",
            },
            {
                "title": "title 3",
                "_id": "2",
            }
        ]
    },
    (...)
]

我想通过他们的评论标题(填充)找到一些文章

var ArticleSchema = new Schema({
    title: { type: String },
    comments: [{ type: Schema.ObjectId, ref: 'Comment' }]
});

我尝试过很多东西:

var options = {
    criteria: {
        'comments.title': regex
    }
};

Article
    .find(options.criteria, function (err, articles) {
        if (err) throw err;
        res.json(articles);
    })
    .populate('comments');

但不起作用......

由于

  • 更新*

这里是我的新代码:三个嵌套的find()和两个forEach()

1 个答案:

答案 0 :(得分:0)

更新中的代码(或类似内容)是使用当前架构执行此操作的唯一方法。但是,我会提出另一个选项,可能会或可能不会与您的其他用例一起使用。

首先,为了确保我们都在同一页面上,我相信当保存到数据库时,您当前的设置实际上看起来像这样:

文章集(单项)

{
    _id: ObjectId("566d820ff8633ffc494998c5"),
    title: "Example Post",
    comments: [
        ObjectId("eed7ceadc82d23441cdbab8c")
    ]
}

评论集(单项)

{
    _id: ObjectId("eed7ceadc82d23441cdbab8c"),
    title: "Example Comment on Example Post"
}

当您ref另一个架构时,这就是它的工作原理。我提出这个问题是因为这与你的文章对象的例子不同。

与关系数据库(如MySQL)不同,MongoDB没有连接。 Populate主要通过运行查询,然后为所有注释ID运行find命令来工作。但是,MongoDB有子文档。如果您要将ArticleSchema更改为以下内容:

var ArticleSchema = new Schema({
    title: { type: String },
    comments: [ CommentSchema ]
});

您的数据库中的数据结构将与您的示例相匹配,并且由于您的所有信息都在一个集合中,因此您可以轻松执行您尝试的搜索。

但是,这可能会使您执行的其他查询更加困难,因此这取决于您的使用案例。