2

I have developed a mean stack application. I am trying to update a record with a null value for the Date field. This is working fine on my localhost but not on my server (Aws Ec2). It contains the previous value before the update.

I have also tried 'undefined' but still same issue.

Visit mongodb set null in update

router.put('/editAssign/:id',(req,res)=>{
    if(!ObjectId.isValid(req.params.id))
        return res.status(400).send('No record with given id : $(req.params.id)');

    var assignment = {
        name: req.body.name,
        code: req.body.code,
        appointmentTime: req.body.appointmentTime,
        scheduledTime:req.body.scheduledTime,
        countEndTime: null
    };

    Assignment.findOneAndUpdate(req.params.id,{$set:assignment},{new:true},(err,doc)=>{
        if(!err)
            res.send(doc);
        else
            console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));
    });
});

I expect it to work on my server too.

Skel
  • 1,611
  • 3
  • 16
  • 36
Abdul Rehman Khan
  • 162
  • 1
  • 4
  • 23

1 Answers1

2

I have done a similar thing with updating the last login date of a user when they log in using Mongoose.

const authUser: any = await new Promise((res, rej) => {
    User.findOneAndUpdate({ _id: user[0]._id }, { last_login: date }, {new: true}, (err: any, user:any) => {
        if (err) rej(err);
        res(user);
    });
});

As you can see I wrapped it in a promise so i can wait for the response for sending back.

From looking at yours I would it looks like you are not telling it to look for using findByIdAndUpdate and not findOneAndUpdate because you are only passing in the ID. So the updated should look like this.

Assignment.findByIdAndUpdate(req.params.id, assignment, {new:true}, (err,doc)=>{
    if(err) console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));

    return res.send(doc);
});

So in the one above, we are passing over the ID for findByIdAnyUpdate and we are just passing in the assignment. which if it includes all the same fields as the schema it will just update with the latest fields.

EDIT:

One other method you could try is:

Assignment.findByIdAndUpdate(req.params.id, assignment, {new: true}, (err: any, result: any) => {
    if(err) console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));

    // Reasign with new assignment and save
    result = assignment;
    result.save();

    return res.send(result);
});
Skel
  • 1,611
  • 3
  • 16
  • 36