我的架构: -
var playlistSchema = new Schema({
name : {type:String,require:true},
videos : {type:[mongoose.Schema.Types.ObjectId],ref: 'Video'},
},{collection:'playlist'})
var Playlist = mongoose.model('Playlist',playlistSchema);
我在数据库中有一些数据作为例子: -
{
"_id" : ObjectId("58d373ce66fe2d0898e724fc"),
"name" : "playlist1",
"videos" : [
ObjectId("58d2189762a1b8117401e3e2"),
ObjectId("58d217e491089a1164a2441f"),
ObjectId("58d2191062a1b8117401e3e4"),
ObjectId("58d217e491089a1164a24421")
],
"__v" : 0
}
视频的架构是: -
var videoSchema = new Schema({
name : {type:String,required:true},
createdAt : {type:String,default:new Date()},
isDisabled : {type:Boolean,default:false},
album : {type: mongoose.Schema.Types.ObjectId, ref: 'Album'}
},{collection:'video'})
var Video = mongoose.model('Video',videoSchema);
现在,为了获取播放列表中所有视频的名称,我正在尝试代码: -
var playlistModel = mongoose.model('Playlist');
let searchParam = {};
searchParam._id = req.params.pid;
playlistModel.findOne(searchParam)
.populate('[videos]')
.exec(function(err,found){
if(err)
throw err;
else{
console.log(found.videos[0].name);
}
})
但是我在这里得到了未定义的结果。我没有得到我错的地方plzz任何人帮我解决这个问题。
答案 0 :(得分:1)
得到了答案: - 只需更改架构
var playlistSchema = new Schema({
name : {type:String,require:true},
videos : [{type:mongoose.Schema.Types.ObjectId,ref: 'Video'}],
},{collection:'playlist'})
var Playlist = mongoose.model('Playlist',playlistSchema);
然后使用
.populate('videos')
而不是
.populate('[videos]')