developKinberg
developKinberg

Reputation: 383

NodeJS & Mongoose, update values in array of objects not working

I am struggling to update some specific arrays in my UserSchema with the mongoose function findByIdAndUpdate().

This is my UserSchema:

const UserSchema = new mongoose.Schema({
    mail: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    friends: [{id: String}],
    prot: [{
        id: String,
        admin: Boolean,
    }]
});

I only want to update the prot element, this is how I want todo this:

User.findByIdAndUpdate(req.body.userId, {
        $set: { prot: [{ id: req.body.lockId, admin: req.body.isAdmin }] }, function(err, user) {
            if (err) {
                return res.status(500).send({
                    message: err.message || "Some error occured while updating user"
                });
            }
            if (!user) {
                return res.status(404).send({
                    message: "User not found"
                });
            }

            return res.status(200).send(user);
        }
    })

But when I try to send a request via Postman, I didn't get an response or error..

Upvotes: 0

Views: 5431

Answers (2)

Nouman Dilshad
Nouman Dilshad

Reputation: 1080

If you want to update a specific record inside an array of objects. You can do it like this.

  User.update(
      { _id: req.body.userId, 
        prot: 
            { $elemMatch: { id: req.body.lockId }}
      },
      { $set: 
            { prot: { admin: req.body.isAdmin }
      }
   },(error,result)=>{
      if(error){ 
         //handle error
      }
      console.log(result);
    } 
    )

Upvotes: 0

Francis Ngueukam
Francis Ngueukam

Reputation: 1024

FindByIdAndUpdate doesn't return updated document per default, you should add option {new:true}. You have mixed brackets too. Do it like below:

User.findByIdAndUpdate(
    req.body.userId, 
    {
       $set: { 
          prot: [{ 
                id: req.body.lockId, 
                admin: req.body.isAdmin 
          }] 
       }
   }, 
   { new: true },
   function(err, user) {
        if (err) {
            return res.status(500).send({
                message: err.message || "Some error occured while updating user"
            });
        }
        if (!user) {
            return res.status(404).send({
                message: "User not found"
            });
        }

        return res.status(200).send(user);
    }
);

Upvotes: 2

Related Questions