我尝试使用类型Comment(另一个模式)定义数组'comments'。
const beerSchema = new Schema({
name:String,
country:String,
color:String,
alcoholPercent:Number,
upvotes:{type:Number, default:0},
comments:[{type:Schema.Types.ObjectId, ref:'comments'
}]
});
收集对象
[
{
"upvotes": 0,
"comments": [],
"test": [],
"_id": "5b0092af2cdf6b30b80dd386",
"name": "newName",
"country": "Belgium",
"color": "blond",
"alcoholPercent": 4.5,
"__v": 0
}
]
我的评论模式类
const mongoose = require('mongoose');
const {Schema } = mongoose;
const commentSchema = new Schema({
_beer:{type:Schema.Types.ObjectId, ref:'beers'},
postedTime:{type:Date, default:Date.now()},
comment:String,
_user:{type:Schema.Types.ObjectId, ref:'User'}
});
mongoose.model('comments', commentSchema);
查询填充:
const newComment = new Comment({
_beer:req.params.id,
comment:'comm1',
// _user:req.user.id
});
newComment.save(function(err){
if(err) return handleError(err);
console.log('new comment saved');
});
Beer.findOne({name:'newName'})
.populate('comments')
.exec(function(err, comment){
if(err) return handleError(err);
console.log('new Comment is %s', comment._beer);
});
当我尝试记录comment._beer时,我的console.log给了我一个未经解决的错误。 有人可以指出我做错了吗?谢谢!
答案 0 :(得分:1)
您的参考模型不正确Comment
...应为comments
const beerSchema = new Schema({
name:String,
country:String,
color:String,
alcoholPercent:Number,
upvotes:{type:Number, default:0},
comments:[{type:Schema.Types.ObjectId, ref:'comments'}]
}