0

I have the following model in the mongoose schema. In this model Messages is the array of objects.

{
"_id" : ObjectId("5a4e6e0f003db94a2c6e52d3"),
"IsGroup" : false,
"GroupName" : "Group1",
"Messages" : [ 
    ObjectId("5a4e6e53003db94a2c6e52d4"), 
    ObjectId("5a4e6e56003db94a2c6e52d5"), 
    ObjectId("5a4e6e58003db94a2c6e52d6"), 
    ObjectId("5a4e6e5b003db94a2c6e52d7"), 
    ObjectId("5a4e6e60003db94a2c6e52d8"), 
    ObjectId("5a4e6e63003db94a2c6e52d9"), 
    ObjectId("5a4e6e65003db94a2c6e52da"), 
    ObjectId("5a4e6e68003db94a2c6e52db"), 
    ObjectId("5a4e6e72003db94a2c6e52dc"), 
    ObjectId("5a4e6e77003db94a2c6e52dd"), 
    ObjectId("5a4e6e7d003db94a2c6e52de"), 
    ObjectId("5a4e6e80003db94a2c6e52df")
 ]
 "__v" : 0
}

I am trying to get the last 5 messages form the array. I achieved this by the following code. Model is my mongo model.

Model.UserGroupModel.findById(GroupId)
    .select({ Messages: { '$slice':-5}})
    .exec(function (err, GroupResult) {
}

But my challenge is to get the next previous 5 elements which are need to start form previous item.

ex: In first result I have to get following result.

ObjectId("5a4e6e68003db94a2c6e52db"), 
ObjectId("5a4e6e72003db94a2c6e52dc"), 
ObjectId("5a4e6e77003db94a2c6e52dd"), 
ObjectId("5a4e6e7d003db94a2c6e52de"), 
ObjectId("5a4e6e80003db94a2c6e52df")

In next request I have to get. I will pass the input of previously returned objectId("5a4e6e68003db94a2c6e52db") for where the next result start point to get.

ObjectId("5a4e6e58003db94a2c6e52d6"), 
ObjectId("5a4e6e5b003db94a2c6e52d7"), 
ObjectId("5a4e6e60003db94a2c6e52d8"), 
ObjectId("5a4e6e63003db94a2c6e52d9"), 
ObjectId("5a4e6e65003db94a2c6e52da"),

How to query this one in mongoose?

1 Answer 1

2

You can try below aggregation function for fetching next records in 3.4 version.

Model.UserGroupModel.aggregate([
  {"$match":{"_id":GroupId,"Messages":MessageId}},
  {"$project":{
    "Messages":{
      "$slice":[
        "$Messages",
        {"$subtract":[{"$indexOfArray":["$Messages",MessageId]},5]}
        ,5
      ]
    }
  }}
]).exec(function (err, GroupResult) {}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.