Bhoomika Chauhan Bhoomika Chauhan - 1 year ago 97
Node.js Question

Mongoose findByIdAndUpdate method to toggle and update a Boolean value in database

I'm trying to toggle and update a boolean value in database whenever a button is clicked..


<form action="/browse/<%= book._id %>/sold" method="GET">
<button type="submit"> Mark As Sold </button>


var bookSchema = new mongoose.Schema({
title: String,
description: String,
sold: { type:Boolean, default: false }

I've tried to use this on the .get route :

Book.findByIdAndUpdate(, {$set: {sold: !sold} }, function(err, book){

but it doesnt work.. (sold is undefined)

I'm new to express and mongoose and searched on google a lot but couldnt find a solution. Please help.
is there any other way to solve this?

Answer Source

The method you are using will not work. You are referencing an undeclared variable sold in this snip: {sold: !sold}. If anything, you'd want to do {sold: !this.sold}, but this within a findById is a query and not the model. You would have to use findById for the book you want, update it manually (book.sold = !book.sold) then save it.

You could create a static method on your model to accomplish all this.

It would look something like

bookSchema.statics.findByIdAndToggleSold = function(id, callback){ // Your code to find, then update here. }