Bdyce
Bdyce

Reputation: 332

Mongoose get updated document after instance.update()

I am executing a mongoose Model.findById() function in order to return a single instance by utilizing an express route.

Model.findById(modelid)
        .then(instance => {
            if(instance.isOwnedBy(user)) {
                return instance.update({$push: {days: req.params.dayid}}, {new: true})
                               .then(foo => res.send(foo))
            } else {
                res.status(401).send("Unauthorized")
            }
        })

the above code returns an object containing the opTime, electionId...etc instead of returning the newly updated document instance. How am I able return the newly updated document after the instance.update() method?

Upvotes: 0

Views: 265

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

If instance.isOwnedBy(user) and _id: modelid can be merged into one mongo query, it's better to use findOneAndUpdate() but in that way, if it doesn't find any document match, you can not know which part of the query causes the not found.

And because I don't know much about your models, conditions, I can not answer how to do it with findOneAndUpdate() but there is another way that modify the document and call save() method.

Example base on your code:

Model.findById(modelid)
    .then(instance => {
        if(instance && instance.isOwnedBy(user)) {
            if(instance.days) instance.days.push(req.params.dayid);
            else instance.days = [req.params.dayid];
            instance.save().then(function(instance){
              res.send(instance);
            })
        } else {
            res.status(401).send("Unauthorized")
        }
    })

Note: You should check if the instance exist or not before modify it.

Upvotes: 1

Related Questions