Mongoose 更新 ref 和 populate ref的问题
环境:
- Mongodb 3.6.3
- mongoose: 5.2.5
- nodeJS: 8.X
描述:
- 模拟博客系统,有两个collection( articles / comments), schema 如下
// article model
const ArticleSchema = new Schema({
title: String,
author: String,
content: String,
lastModified: {type: Date, default: Date.now()},
// comments collections refs
comments: [{type: Schema.Types.ObjectId, ref: 'comments'}],
meta: {
tags: {type: Array, default: []},
votes: {type: Number, default: 0}
}
});
// comments model
const CommentSchema = new Schema({
// DBref to article collection
article: {
type: Schema.Types.ObjectId,
ref: 'article'
},
// For unlogined user
tempNick: String,
// For future logined user
status: Schema.Types.ObjectId,
content: String,
replies: [
{
// name for both logined & unlogined
name: '',
content: String,
createdTime: {
type: Date,
default: Date.now()
}
}
],
createdTime: {
type: Date,
default: Date.now()
}
});
article 和 comment 是一对多的关系,因此在发布评论的方法上我是这样做的:
// Write comment
exports.postComment = function(req, res) {
let request;
let aid;
console.log(chalk.green('WRITING COMMENTS'));
request = req.body;
request._id = new mongoose.Types.ObjectId();
aid = req.params.aid;
let comment = new Comment(request)
comment.save(function(err) {
if (err) {
errCallback(err, res);
} else {
// let article = new Article({
// comments: comment._id
// })
Article.findByIdAndUpdate(aid, {$push: {comments: request._id}}, function (err, com) {
if (err) {
errCallback(err);
}
console.log('----------');
})
postSuccessCallback('post comment success', res);
}
})
}
嗯,结果是可以写入成功的,写入两次并通过mongoshell查询发现该article文档内的comments数组字段有两个内容[ObjectId(*************),ObjectId(****************)]
但是,通过组织Mongoose来进行查询却返回undefined:
// Query for comment
// Params: { offset / limit / sortBy }
exports.getComments = function(req, res) {
let count;
let data;
let { offset, limit, sortBy } = req.query;
let { aid } = req.params
// Get Total count
Comment.estimatedDocumentCount(function(err, num) {
if (err) {
errCallback(err, res);
return
}
count = num;
});
offset = Number(offset);
limit = Number(limit);
console.log('aid', aid);
Article.findById(aid).
populate('comments').
// skip(offset).
// limit(limit).
// sort(dueSortby(sortBy)).
exec((err, comment) => {
console.log('execed!', comment)
data = comment;
getCountCallback(data, count, res);
});
}
篇幅啰嗦,恐怕丢掉细节,如有解答望不吝告知!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论