Ross
Ross

Reputation: 141

Adding to an array in MongoDB using $addToSet

I'm trying to add data to an array defined in my mongoDB called "signedUp" it is within my Timetable Schema. So far i've been able to update other fields of my schema correctly however my signedUp array always remains empty. I ensured the variable being added was not empty.

Here is my Schema

var TimetableSchema = new mongoose.Schema({

date: {
    type: String,
    required: true,
    trim: true
  },
  spaces: {
    type: Number,        
    required: true
  },
  classes: [ClassSchema],
  signedUp: [{
    type: String
  }]


});

This was my latest attempt but no value is ever added to the signedUp array. My API update request

id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id,space,signedUp,function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

Thanks

Upvotes: 3

Views: 200

Answers (2)

f-person
f-person

Reputation: 329

space and signedUp are together the second argument.
try this:

id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id, {...space, ...signedUp}, function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

Upvotes: 1

mickl
mickl

Reputation: 49945

You can take a look at db.collection.update() documentation. Second parameter takes update and 3rd one represents operation options while you're trying to pass your $addToSet as third param. Your operation should look like below:

id = {_id: req.params.id};
space = { $set: { spaces: newRemainingCapacity }};
signedUp = { $addToSet:{ signedUp: currentUser}};
update = { ...space, ...signedUp }

Timetable.update(id,update,function(err, timetable){
    if(err) throw err;
    console.log("updates");
    res.send({timetable});
});

Upvotes: 2

Related Questions