简体   繁体   中英

Mongoose find in object array value

Example of Article object array:

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

I would like to find some articles by their comments title (populated)

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

I tried a lot of things like:

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

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

but does not work...

Thanks

  • Update *

Here my new code: three nested find() and two forEach()

The code in your update (or something similar) is the only way to do it with your current schema. However, I will propose another option which may or may not work with the rest of your use case.

First, just to make sure we're both on the same page, I believe your current setup would actually look something like this when saved to the database:

Articles Collection (A Single Entry)

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

Comments Collection (A Single Entry)

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

This is how it works when you ref another schema. I bring this up because this is different than your example of an article object.

Unlike relational databases (such as MySQL), MongoDB doesn't have joins. Populate essentially works by running your query, and then running a find command for all the comment IDs. However, MongoDB has subdocuments. If you were to change your ArticleSchema to something like this:

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

Your data structure in the database would match your example, and since all of your information would be in one collection, you could easily perform the search you're trying to.

However, this may make other queries you perform more difficult, so it depends on your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM