简体   繁体   English

如果文档的 _id 已经存在,如何将数组元素推送到数组,如果 _id 不存在,如何创建新文档?

[英]How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?

I am using Node.js , mongoose , mongodb , express and angular .我正在使用Node.jsmongoosemongodbexpressangular I am saving replies for a survey in a mongoose model.我正在保存对猫鼬模型中调查的答复。 Many people will submit replies for a particular survey.许多人会针对特定调查提交答复。 When the first person submits a reply for a survey, I want to create a new document for that survey.当第一个人提交调查回复时,我想为该调查创建一个新文档。 When the second, third.... so on people submit replies for the same survey, I want to add array elements only to the replies array in the following schema.当第二个、第三个......等人们提交对同一调查的回复时,我只想将数组元素添加到以下架构中的回复数组中。

And when the first person submits a reply for a new survey I want to create a new document for the new survey.当第一个人提交新调查的回复时,我想为新调查创建一个新文档。 How can I do this in mongoose?我怎么能在猫鼬中做到这一点?

I found similar question in Mongoose.js: how to implement create or update?我在Mongoose.js 中发现了类似的问题:如何实现创建或更新? . . But, here I want to push the new replies to the next array index of replies[] if the _id is found, else create a new document但是,如果找到 _id,我想在这里将新回复推送到下一个回复 [] 数组索引,否则创建一个新文档

mongoose model :猫鼬模型

 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);

Saving data to database :将数据保存到数据库

      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("/");

    });

   });

pseudo untested code.未经测试的伪代码。

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


    })

Don't know if this will work but if your having trouble just saving the _id try this for Schema()不知道这是否可行,但如果您在保存 _id 时遇到问题,请尝试将其用于 Schema()

var MCQReplySchema = new Schema({ 

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

    }, {strict : false});

if {strict :false} doesn't work如果{strict :false}不起作用

try {strict : false, _id :false} or just _id : false尝试{strict : false, _id :false}或只是_id : false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NodeJS, Mongoose 如果 ID 存在则什么都不做,如果不存在则将新的推入数组 - NodeJS, Mongoose if ID exists do nothing, if doesn't exist push the new one to the array 设置字段(如果不存在),推送到数组,然后返回文档 - Set field if doesn't exist, push to array, then return document 如何循环遍历 mongoose id 数组以检查它是否有效并且它确实存在于数据库中,然后推送到一个新数组 - How do I loop through an array of mongoose id to check if it's valid and it does exist in the DB then push to a new array 如果该字段已经存在于文档中,猫鼬将停止以$ push进行数组 - Mongoose stops to $push to array if the field already exists in a document 如何在文档中查找包含数组中所有元素的文档? - how to find documents with all elements in the array in the document? Mongodb:查找具有数组的文档,其中所有元素都存在于查询数组中,但是文档数组可以更小 - Mongodb: find documents with array where all elements exist in query array, but document array can be smaller 猫鼬-如何将文档添加到具有该文档ID的数组 - Mongoose - How add documents to array that has id of that documents MongoDB 和 API 集成 - 如果不存在则创建新用户 - MongoDB and API integration - Create New User if Doesn't Already Exist 创建新的Mongodb文档与推送到文档数组 - Create new Mongodb Documents vs Pushing to a Document's Array 如果 MongoDB 中不存在用户名或电子邮件,则创建新文档 - Create new document if username or email doesn't exists in MongoDB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM