Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 674
Ross Avatar asked Jan 26 '26 19:01

Ross


1 Answers

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});
});
like image 108
mickl Avatar answered Jan 29 '26 10:01

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!