【问题标题】:How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?如果文档的_id已经存在,如何将数组元素推送到数组中,如果_id不存在,如何创建新文档?
【发布时间】:2017-07-28 14:51:05
【问题描述】:

我正在使用Node.jsmongoosemongodbexpressangular。 我正在保存猫鼬模型中调查的回复。许多人会为特定调查提交答复。当第一个人提交调查回复时,我想为该调查创建一个新文档。当第二个,第三个....等人为同一个调查提交回复时,我只想将数组元素添加到以下架构中的回复数组。

当第一个人为新调查提交回复时,我想为新调查创建一个新文档。我怎样才能在猫鼬中做到这一点?

我在Mongoose.js: how to implement create or update? 中发现了类似的问题。 但是,如果找到_id,我想将新回复推送到回复[]的下一个数组索引,否则创建一个新文档

猫鼬模型

 var mongoose = require("mongoose");
 var Schema = mongoose.Schema;

 var MCQReplySchema = new Schema({ 

    _id : String,
    surveyname: String,
    replies :[{
        replierId : String,
        answers : [{
            questionId : String,
            answer : String
        }]  
    }]

    });

 module.exports=mongoose.model('MCQReply',MCQReplySchema);

将数据保存到数据库

      router.post("/saveMCQAnswer", function(req, res) {

       new MCQReply({

       _id : '123',
        surveyname: 'sample',
        replies :[{
          replierId : 'R001',
          answers : [{
            questionId : 'A001',
            answer : 'answer'
          }]  
        }]

    }).save(function(err, doc){
      if(err) res.json(err);
      else
      req.flash('success_msg', 'User registered to Database');  
      res.redirect("/");

    });

   });

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

伪未经测试的代码。

    MCQReply.findOne({_id : the id}, function(err,doc){
        if(err) console.log(err);
        // if the survey isn't there `doc` will be null then do your save
        if(!doc){
          new MCQReply({

           _id : '123',
            surveyname: 'sample',
            replies :[{
              replierId : 'R001',
              answers : [{
                questionId : 'A001',
                answer : 'answer'
              }]  
            }]

            }).save(function(err, doc){
              if(err) res.json(err);
              else
              req.flash('success_msg', 'User registered to Database');  
              res.redirect("/");

            });                 
        }else(doc){
            //you get mongoose document
            doc.replies.push({replierId : "R001", answer : [{questionId : "A001" ... whatever else you want}]})

            //dont forget to save
            doc.save(do error check)
        }


    })

不知道这是否可行,但如果您在保存 _id 时遇到问题,请尝试使用 Schema()

var MCQReplySchema = new Schema({ 

    _id : String,
    surveyname: String,
    replies :[{
        replierId : String,
        answers : [{
            questionId : String,
            answer : String
        }]  
    }]

    }, {strict : false});

如果{strict :false} 不起作用

试试{strict : false, _id :false} 或只是_id : false

【讨论】:

  • 感谢您的回答。但是,我遇到了一些问题。 doc.replies.push({replierId : "R002", answer : [{questionId : "A002"},{answer : "A001"}]});我修改了你的代码。对于第一个大多数回复,它没有保存回复者 ID 和问题 ID。对于第二个回复,再次没有回复者 ID,并且答案 [] 中没有任何内容。你能帮我解决这个问题吗?
  • 架构在上述问题中。我在 Robomongo 中上传了架构的屏幕截图。如果被接受,它将是可见的。
  • 如果将 strict :false 添加到 schema 选项会怎样。任何变化。新Schema({}, strict :fasle)
  • 好的已编辑。 strict 用于保存不在schema 中的东西,所以也许你有这种类型的问题。和 _id false 我认为有助于不显示 _id 如果您使用自己的 _id 或告诉 mongo 不要生成自己的 _id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2021-04-21
  • 1970-01-01
  • 2015-09-17
  • 2021-09-12
  • 2019-10-21
相关资源
最近更新 更多