2015-10-04 125 views
3

我正在嘗試保存帖子的評論。當我從客戶端發佈評論時,評論應該與帖子的ObjectId一起保存,該帖子是我從帖子頁面收集的 - req.body.objectId。我已經嘗試了下面的方法,但它只給了我驗證錯誤。貓鼬用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' 
    } 

我怎樣才能做到這一點?這是實現這種功能的正確方法嗎?先謝謝你。

回答

4

這不是插入引用類型值的正確方法。

你要做像,

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

按你們的要求它將工作。

+0

謝謝!有用! – sawa