sunny
sunny

Reputation: 125

Patch (findByIdAndUpdate) in Mongoose

I have to do a simple CRUD in Node/Mongoose API. I also have to make put and patch and while doing patch, I'm a bit confused, because I wanted to use findByIdAndUpdate method, but as I see on examples, there is only one record updated, e.g. {name: "newName"}. I was wondering what I should do if for example I wanted to update two cells?

My schema:

const userSchema = new Schema({
    login: String,
    email: String,
    registrationDate: Date,
});

My Patch code:

router.patch('/:id', async (req, res) => {
    const id = req.params.id;
    User.findByIdAndUpdate(id, { ??? },
        function (err, docs) {
            if (err){
                console.log(err)
            }
            else{
                console.log("Updated User : ", docs);
            }
        });

});

I don't know what I should write in "???", because what if I wanted to update only the login, and what if I wanted to update name and email? Maybe I'm wrong and PATCH is used only to edit ONE cell and in other cases I should use PUT?

Edit:

I made it work using something like this:

router.patch('/:id', async (req, res) => {
    const id = req.params.id;
    let updates={}
    if (req.body.login) {
        updates["login"] = req.body.login
    }
    if (req.body.email) {
        updates["email"] = req.body.email
    }
    if (req.body.registrationDate) {
        updates["registrationDate"] = req.body.registrationDate
    }
    User.findByIdAndUpdate(id, updates,
        function (err, docs) {
            if (err){
                console.log(err)
            }
            else{
                console.log("Updated User : ", docs);
            }
        });

});

Anyway I have a question what I should do to "stop" the action. I'm using HTTPie and when I write http PATCH......, it seems like I can't write anything else, because it's still working, I need to do CTRL+C to stop the query.

Upvotes: 0

Views: 1976

Answers (1)

BroscR
BroscR

Reputation: 167

Just write the fields you want to change and the new values ​​separated by commas.

const id= req.params.id;
const email = "newemail";
const date = "1991/13/01";
const user = await User.findByIdAndUpdate(
    {
      _id: id,
    },
    { email, registrationDate: date},
    { upsert: false }
  );

Upvotes: 1

Related Questions