Reputation: 815
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 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
}
Upvotes: 0
Views: 1356
Reputation: 3154
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();
Upvotes: 2