node.js - 填充对象ID的数组

标签 node.js mongodb mongoose

我的架构:

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]')

关于node.js - 填充对象ID的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42976483/

相关文章:

javascript - 使用 Mongoose 通过传递选项 JSON 来过滤数据 DB 级别

node.js - 一次删除多个认知用户时出现 TooManyRequestsException : Rate exceeded.

javascript - Mongodb Nodejs : return undefined after callback of an exported function

javascript - typescript :调试失败。错误表达式:传递给 `ts.resolveTypeReferenceDirective` 的非字符串值

javascript - Angular/javascript : Read values from a GET

node.js - 如何在 mongoose 中设置 objectId 属性?

javascript - Sequelize : Bulk update or insert into MSSQL DB

mongodb - $在mongodb中查找嵌套数组

node.js - 阻止 Mongoose 为子文档数组项创建 _id 属性

javascript - Mongoose Populate 以获取用户的所有帖子返回空数组