简体   繁体   中英

Express: POST data to an array mongoose & node

I'm building a simple app where a company sends out a question to its employees requesting for feedback. I'm struggling to put MORE employees(users) in the question document as an array. Right now it only inserts one employee. Basically what I require is for each question to have employees respond to it & also to be able to (in future) query the db for all questions an employee has answered. Here are my Schemas.

Here's the previous issue that was solved - for anyone interested.

Models

var QuestionSchema = Schema({
    id          : ObjectId,
    title       : String,
    employees   : [{ type: ObjectId, ref: 'User'}]
});

module.exports = mongoose.model('Question', QuestionSchema);  

var UserSchema = Schema({
    username    : String,
    response    : String,
    questions   : [{ type: ObjectId, ref: 'Question'}]
});

module.exports = mongoose.model('User', UserSchema);

api.js

         Question.findOne({ title: 'Should we buy a coffee machine?'}).exec(function(err, question) {
              //example: is this the right way of creating the array
              var user = new User([{
                "username": "lindelof",
                "response": "yes",
              },{
                "username": "bailly",
                "response": "no",
              },{
                "username": "suzan",
                "response": "yes",
              }]);

              question.employees = [user1._id];
              user.questions = [question._id];

              question.save(function(err) {
                  if (err) throw err;
                  console.log(question);
                  user1.save(function(err) {
                      if (err) throw err;
                  });
              });

            });
            console.log('entry saved to answer >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
        }

在此处输入图片说明

在此处输入图片说明

I would modify your api.js this way:

Question.findOne({ title: 'Should we buy a coffee machine?'}).exec(function(err, question) {
  const userData = [{
    "username": "lindelof",
    "response": "yes",
  },{
    "username": "bailly",
    "response": "no",
  },{
    "username": "suzan",
    "response": "yes",
  }];

  for (const user of userData) {
    const userModel = new User(user);
    userModel.questions = [question._id];
    // Its async, but in this example - no need to wait untill it is executed
    userModel.save();
    question.employees.push(userModel._id);
  }

  question.save(function(err) {
    if (err) throw err;
    console.log(question);
  }
});

Also, I can suggest you to look in the side of promises/generators or async/await approaches. It becomes much more easier to read then.

Same code formatted with async/await:

async function doJob() {
  const question = await Question.findOne({ title: 'Should we buy a coffee machine?'});

  const userData = [{
    "username": "lindelof",
    "response": "yes",
  },{
    "username": "bailly",
    "response": "no",
  },{
    "username": "suzan",
    "response": "yes",
  }];

  for (const user of userData) {
    const userModel = new User(user);
    userModel.questions = [question._id];
    await userModel.save();
    question.employees.push(userModel._id);
  }

  await question.save();
  console.log(question);

};

// And sure we have to call this function somewhere...
doJob();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM