2

I am using MongoDB and Mongoose. I currently have a like button, and when I click it I would like to increment the 'likes' field in my document. Currently my document has the following schema:

brote {
  name: 
  content:
  created: 
  likes: 
} 

and I have tested that the ID in my query matches that of the object in my database.

I consulted How do I increment a Number value in Mongoose? and Incrementing a value with mongoose? but these solutions did not seem to make any changes to my database. Perhaps there is something blatantly obvious that I am missing?

Index.js

mongoose.connect('mongodb://localhost:27017/bromies', { useUnifiedTopology: true, useNewUrlParser: true });
mongoose.set('useFindAndModify', false);
var Brote = mongoose.model('Brote', broteFormSchema);

app.post('/likes', (req, res) => {
    let query = { id: req.body._id};
    Brote.findOneAndUpdate(query, {$inc: { 'likes': 1 }});

  })
David Buck
  • 3,752
  • 35
  • 31
  • 35
FlackoNeil
  • 23
  • 1
  • 6
  • 1
    Check the query object I think it should be {_id: req.body._id}. I will like to know the data type for the likes in your model – Quajo Duke May 01 '20 at 02:16
  • @QuajoDuke I changed id to _id and it still does not change the field :( The datatype is Number – FlackoNeil May 01 '20 at 02:28
  • Did you try doing this :: (https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) ? I guess that should solve your issue, If not How does your `Brote` schema look like & also provide sample docs.. – whoami - fakeFaceTrueSoul May 01 '20 at 03:06
  • Did also try adding {new: true} option to the findOneAndUpdate. Or do this: `const brote = Brote.findById(query); Brote.UpdateOne(query, {$set: {'likes': brote.likes + 1}})` – Quajo Duke May 01 '20 at 03:54

1 Answers1

6

It seems the findOneAndUpdate method does not work without a callback. Try passing a callback like this:

    let query = { _id: req.body._id}; // It is _id, not id
    Brote.findOneAndUpdate(
        query, 
        {$inc:{ likes: 1}},
        (err, brote) => {    // callback
            console.log(brote);
        }
    )  

Edit:
The reason it won't work is because it returns a Query if callback is not passed to it. You can call .exec() on the returned Query to execute it.

From the docs of findOneAndUpdate():

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes if callback is passed.

Kashinath Patekar
  • 1,083
  • 9
  • 23