Mongoose使用objectId进行保存

6

我正在尝试保存帖子的评论。当我从客户端POST一条评论时,评论应该被保存并关联到帖子的ObjectId上,这个ObjectId我是从帖子页面收集的 - req.body.objectId。我尝试了下面的方法,但只给了我验证错误。

模型

var Comment = db.model('Comment', {
    postId: {type: db.Schema.Types.ObjectId, ref: 'Post'},
    contents: {type: String, required: true}
}  

POST

router.post('/api/comment', function(req, res, next){
    var ObjectId = db.Types.ObjectId; 
    var comment = new Comment({
        postId: new ObjectId(req.body.objectId),
        contents: 'contents'
    }

我该如何实现这个功能?这是实现此类功能的正确方法吗?提前感谢您。
2个回答

7

这不是插入引用类型值的正确方式。

你需要像这样做:

router.post('/api/comment', function(req, res, next){
    var comment = new Comment({
        postId: db.Types.ObjectId(req.body.objectId),
        contents: 'contents'
    }

它将按照您的要求正常工作。

5
你需要使用 mongoose.Types.ObjectId() 方法将对象 ID 的字符串表示转换为实际的对象 ID。
var mongoose = require('mongoose');

router.post('/api/comment', function(req, res, next){
    var comment = new Comment({
        postId: mongoose.Types.ObjectId(req.body.objectId),
        contents: 'contents'
    })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接