0

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..

2 Answers 2

2

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

Comments

0

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

Comments

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.