使用objectId保存Mongoose

时间:2015-10-04 14:52:15

标签: node.js mongodb mongoose

我正在尝试为帖子保存评论。当我从客户端发布评论时,评论应该与帖子的ObjectId一起保存,我将从帖子页面收集 - req.body.objectId。我尝试了下面的方法,但它只给了我验证错误。

MODEL

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 个答案:

答案 0 :(得分:4)

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

你必须这样做,

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

它可以按你的意愿工作。

答案 1 :(得分:0)

您需要使用 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'
}
相关问题