A-Sharabiani
A-Sharabiani

Reputation: 19377

Return the size of array property after updating

Description


Trying to create a "like button" for blog posts; which stores the likes based on IP address.

This is a sample document in my collection called blogs:

{ _id:123123,
  title: "title here",
  desc: "some other text here",
  likes: [
   {ip: "10.0.0.1"},
   {ip: "0.1.1.1"},
  ]
}

After the user clicks the like button, the document gets updated using the code below:

 dbo.collection('blogs').findOneAndUpdate(
            {_id:ObjectId(id)},
            {$addToSet: {likes: {ip: uip}}},
            {}, // TODO: options
            function(err, res) {});

Question


What I tried..


I tried passing the following as the options (the TODO line):

{"projection":{ numOfLikes:{ $size: {"$ifNull" : ["$likes", []]}}} }

However, it throws an exception since numOfLikes is not a property of the document.

Note


I am using mongodb with node.js, using the official mongodb driver for node.js

Upvotes: 0

Views: 40

Answers (1)

GuillaumeHaben
GuillaumeHaben

Reputation: 96

Based on https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/, did you try the returnNewDocument option? You should be able to access the likes array from the return object of your function and get its new length. Something like:

dbo.collection('blogs').findOneAndUpdate(
            {_id:ObjectId(id)},
            {$addToSet: {likes: {ip: uip}}},
            {returnNewDocument: True},
            function(err, res) { console.log(res.likes.length) });

Upvotes: 1

Related Questions