[英]How can I query MongoDB sub documents using mongoose?
I have my schemas for ActorCollections and Movies: 我有ActorCollections和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. 我想形成一个查询,该查询首先找到正确的actorCollection,然后从该actorCollection.movies数组中找到某个属性的电影。
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. 我也看到了使用$ elemMatch查找嵌套在子文档中的项目的方法,但是我不确定如何首先通过ActorCollection进行过滤。 If multiple actors appear in the same movie, I cannot tell which ActorCollection I will be modifying.
如果同一部电影中出现多个演员,则无法确定要修改哪个ActorCollection。
Any ideas? 有任何想法吗? Can I combine queries somehow to achieve this?
我可以以某种方式组合查询来实现此目的吗?
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
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.