简体   繁体   中英

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

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});
});

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});
});

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