Reputation: 2988
I have an express route using mongoose. This .findByIdAndUpdate isn't working. I see the "removeId" come in, the second console.log shows the correct record... but it didn't update! Am I doing something wrong here?
router.post('/highlight', jsonParser, (req, res) => {
const { removeId, addId } = req.body;
console.log('removeId', removeId)
Article
.findByIdAndUpdate(removeId, {
featured: false
})
.then(updatedArticle => {
console.log('updated article', updatedArticle)
Upvotes: 1
Views: 265
Reputation: 18515
Mongodb findOneAndUpdate
method has an option called returnNewDocument
which as per the documentation:
Optional. When true, returns the updated document instead of the original document. Defaults to false.
Mongoose wraps that method but it calls its pass through option new
as per its code/documentation:
outer.post('/highlight', jsonParser, (req, res) => {
const { removeId, addId } = req.body;
console.log('removeId', removeId)
return Article.findByIdAndUpdate(removeId, {featured: false}, {new: true})
.then(updatedArticle =>
console.log('updated article', updatedArticle)
)
})
Also do not forget the return
your Article.findByIdAndUpdate
in your post method.
Upvotes: 0
Reputation: 14060
It's a strange default but findByIdAndUpdate doesn't return the updated record by default. You have to pass {new:true} to get it.
router.post('/highlight', jsonParser, (req, res) => {
const { removeId, addId } = req.body;
console.log('removeId', removeId)
Article
.findByIdAndUpdate(removeId,{new: true}, {
featured: false
})
.then(updatedArticle => {
console.log('updated article', updatedArticle)
Upvotes: 2