0

I have a schema of chat where the fields are like :

[{
 "text" : "xyz",
 "userId" :ObjectId("1")  // mongoId which reference User schema
 "count" : 1
},
{
 "text" : "xyz-1",
 "userId" :ObjectId("2")  // mongoId which reference User schema
 "count" : 1
},
{
 "text" : "xyz-2",
 "userId" :ObjectId("1")  // mongoId which reference User schema
 "count" : 2
}]

What I want to do here is whenever I insert a new document in chat schema it checks if the userId is already their, if yes then just insert the document with increase the count otherwise start the count with '1'. So If I insert a new document with userID '1' then this time count should be '3' as per above example.

Edit: The only purpose of asking this question is can I handle this scenario without extra mongo call?

Himanshu Teotia
  • 2,126
  • 1
  • 27
  • 38

1 Answers1

0

Just try with this

function getNextSequence(id) {
 var ret = db.collection.aggregate([
      {$match:{userId: id}}
]).toArray();
if(ret.length) {
    return ++ret[ret.length-1].count;
}
else return 1
}


db.collection.insert(
{
 name: "Sarah C.",
"userId" : ObjectId("5c74ddb8fc3e023d9ab588b8"),
 count:getNextSequence(ObjectId("5c74ddb8fc3e023d9ab588b8"))
})   
Ashwanth Madhav
  • 1,084
  • 1
  • 9
  • 21