【问题标题】:Mongoose saving with objectId使用 objectId 保存猫鼬
【发布时间】:2016-01-01 07:03:52
【问题描述】:

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

型号

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

发布

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'
    }

我怎样才能做到这一点?这是实现此类功能的正确方法吗?提前谢谢你。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    你必须这样做,

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

    它会按照你的意愿工作。

    【讨论】:

      【解决方案2】:

      您需要使用 mongoose.Types.ObjectId() 方法将 Object ID 的 String 表示形式转换为实际的 Object 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'
          })
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-27
        • 2017-10-24
        • 2017-04-06
        • 2016-02-09
        • 2020-07-25
        • 1970-01-01
        • 2016-11-21
        • 2016-11-06
        • 1970-01-01
        相关资源
        最近更新 更多