用objectId保存猫鼬

saw*_*awa 4 mongoose mongodb node.js

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

模型

var Comment = db.model('Comment', {
    postId: {type: db.Schema.Types.ObjectId, ref: 'Post'},
    contents: {type: String, required: true}
}  
Run Code Online (Sandbox Code Playgroud)

开机自检

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'
    }
Run Code Online (Sandbox Code Playgroud)

我该如何实现?这是实现此类功能的正确方法吗?先感谢您。

Gau*_*dhi 6

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

你必须这样做

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

它将按照您的要求工作。


Alp*_*til 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'
    })
}
Run Code Online (Sandbox Code Playgroud)