Reputation: 19377
Description
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
TODO
line in the code above, so that the function return the total number of likes
in the document, after updating it? (for example: {numOfLikes: 3}
)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
mongodb
with node.js
, using the official mongodb driver for node.js
Upvotes: 0
Views: 40
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