colin_dev256
colin_dev256

Reputation: 815

POST data does not save arrays

I am new to Mongo and Express. I'm building a simple app where a company sends out a question to its employees requesting for feedback. I'm struggling to put employees(users) in the question document as an array. Here are my Schemas [Not sure if I've written them correctly].

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

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

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

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

api.js

router.post('/', function (req, res) {
    // make sure user is authenticated
    User.findOne({ username: req.body.username }).exec(function(err, user) {
        if(err) throw err;

        if(!user) {
            res.json({ success: false, message: 'Could not authenticate user' })
        } else if (user){

            /*----------------save example----------------------*/
            var question = new Question({ title: 'Should we buy a coffee machine?'});

            question.save(function (err) {
                if (err) throw err;

                var user1 = new User({
                  username: "marcopolo",
                  response: "yes",
                });

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

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

enter image description here

UPDATE (employees table)

enter image description here

Upvotes: 0

Views: 92

Answers (1)

Talha Awan
Talha Awan

Reputation: 4619

It's because you're not actually passing an array of user references to employees field.

var question = new Question({ title: 'Should we buy a coffee machine?', employees: [array of user references]});

How you plan to do that is another matter. You can either pass the array in post request if users are available, in which case it'll be available in req.body.employees, or pass the ids of the user and question you're just creating to each other.

var question = new Question({
    title: 'Should we buy a coffee machine?'
});
var user1 = new User({
    username: "marcopolo",
    response: "yes",
});

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

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

Upvotes: 2

Related Questions