簡體   English   中英

填充對象 ID 數組

[英]Populating in array of object ids

我的架構:-

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);
    }
})

但在這里我得到了未定義的結果。我沒有弄明白我錯在哪里,請有人幫我解決這個問題。

得到了答案:-只需更改架構

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]')
const app = await this.appModel.findOne({ slug }) .populate({ path: 'category', populate: { path: 'subCategories', model: 'Category', select: { name: 1, slug: 1, _id: 0 } }, });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM