简体   繁体   中英

How can I query MongoDB sub documents using mongoose?

I have my schemas for ActorCollections and Movies:

var mongoose = require("mongoose");

var movieSchema = new mongoose.Schema({
    title : String,
    score : Number,
    year : String,
    imdbId : String,
    timestamp: { type : Date, default: Date.now },
});
var actorCollectionSchema = new mongoose.Schema({
    imdbId : String,
    movies: [movieSchema],
    actor: String,
    timestamp: { type : Date, default: Date.now },
});

module.exports = mongoose.model('ActorCollection', actorCollectionSchema);

I would like to form a query that first finds the correct actorCollection, then from that actorCollection.movies array find a movie by some property.

I have tried

ActorCollection.findOne({imdbId: imdbId}, function(err, collection){
    //collection.movies is my array
    // any mongoose methods to query this array???
}

I have also seen methods using $elemMatch to find items nested in sub documents, but I am unsure how to first filter by ActorCollection. If multiple actors appear in the same movie, I cannot tell which ActorCollection I will be modifying.

Any ideas? Can I combine queries somehow to achieve this?

Use elemMatch :

ActorCollection
    .findOne({"imdbId": imdbId)
    .elemMatch("movies", {"title":"foo"})
    .exec(cb);

This ended up working for me. I had to split the queries into individual arguments.

ActorCollection.findOne({
        imdbId: imdbId,
    },
    {
        movies: { $elemMatch: {
            title: "Movie title"
        }},
    }, function(err, movie){
        movie
    })

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