3

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

2
  • Both space and signedUp should be passed as a second parameter. Are you trying to update spaces or replace entire document ? Commented Dec 30, 2019 at 19:09
  • @mickl At the moment i have a spaces counter which updates and i want the array signedup to update, so does that mean i need to split them up into two updates? Commented Dec 30, 2019 at 19:13

2 Answers 2

2

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});
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Try to console.log {space, signedUp}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.