【发布时间】:2016-09-28 23:33:42
【问题描述】:
我有两个模型,Post 和 Comment:
我的Post 模型(models/post.js):
var mongoose = require('mongoose');
var Comment = require('../models/comment');
var Schema = mongoose.Schema;
module.exports = mongoose.model('Post', new Schema({
text: {type: String, trim: true},
postedBy: String,
comments: [Comment]
}));
我的Comment 模型(models/comment.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('Comment', new Schema({
user: String,
comment: {type: String, trim: true},
created: {type: Date, default: Date.now(), select: false}
}));
当我尝试创建一个没有任何comments 的新帖子时,帖子创建得非常好。
虽然当我在创建后尝试$push 对帖子发表评论时,没有任何反应。
Post.findOneAndUpdate(
{"_id": req.params.id},
{$push: {comments: {
comment: "Hello World",
user: "933ujrfn393r"
}}
}).exec(function(err, post) {
console.log(post);
res.json({success: true});
});
为什么无法将评论推送到帖子?我的console.log(post) 行只记录undefined,所以不太清楚这里发生了什么。我尝试了Post.findOne({"_id": req.params.id})的简单测试,它成功返回了帖子,所以find查询没有问题。
【问题讨论】:
-
不要为此使用两个不同的集合,而是使用单个集合,在该集合中,您可以分别为字段 cmets 定义架构。