创建引用集合的ObjectId的文档

时间:2017-11-22 02:54:02

标签: mongodb mongoose

拥有一个从用户架构引用ObjectId的postSchema:

var postSchema = new Schema({
    text: { type: String, required: true, maxlength: 140 },
    _creator: { type: mongoose.Schema.ObjectId, ref: 'User', required: true },

});

在我的postController中,如何在创建新帖子时设置_creator属性?:

exports.postCreatePost = function(req, res, next) {
console.log(req.body);

var newPost = new Post({
    text: req.body.text,
    _creator: req.body.User._id // What is this supposed to be in order to reference User's ObjectId?
});

newPost.save(function(err, newPost) {
    res.status(200).json(newPost);
});
}

在尝试使用Postman为现有用户使用PostId发布此JSON时,错误地接收“位置30处的JSON中的意外字符串”错误:

{
    "text": "first test post"
    "_creator": "5a13b3c695fcb47ea5c71308"
}

1 个答案:

答案 0 :(得分:0)

这里你的postSchema应该是这样的,

var postSchema = new Schema({
    text: { type: String, required: true, maxlength: 140 },
    _creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
});

_creator属性的类型应为mongoose.Schema.Types.ObjectId