1 回答
TA贡献1806条经验 获得超5个赞
User.posts是undefined因为.posts是 的实例的属性User。因此,您需要先实例化用户。在这种情况下,通过从 User 集合中查找现有对象。
由于您定义User.posts为原始数组,而不是引用另一个集合,因此代码将如下所示。
create: function (req, res) {
// 1. find the existing user (I guess passport does the job)
db.User.findById(req.body.userid).then((user) => {
// 2. add an post
user.posts.push({
title: req.body.title,
body: req.body.body,
postedBy: req.body.userid,
dateCreated: Date.now(),
comments: [],
});
// 3. persist the changes
user.save();
});
}
如果你想分离集合,我认为这更好,你需要在分离的集合上创建一个新对象,并引用发布的用户。
// Post schema
var postSchema = new Schema({
title: String,
body: String,
postedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
dateCreated: Date,
comments: [{ body: "string", by: mongoose.Schema.Types.ObjectId }],
});
// The controller
create: function(req, res) {
// 1. find the existing user (or you get id from Passport session)
db.User.findById(req.body.userid).then((user) => {
// 2. add an post set "postedBy" as the user
return Post.create({
postedBy: user._id,
title: req.body.title,
body: req.body.body,
dateCreated: Date.now(),
});
});
}
以下是有关引用的官方文档:https ://mongoosejs.com/docs/populate.html
希望这可以帮助。
添加回答
举报