Here I have a document with an array as one filed in it. Looks like:
var UserSchema = new mongoose.Schema({
activities:[{
action:String,
time:Number,
extraInfo:{}
}]
})
And now I want to select this array,
UserModel
.findById(user._id)
.select('activities')
.lean()
.exec((err,user)=>{....})
but I just need the latest, like 20, activity records.
is there any way to limit the length of selected array?
You can use the MongoDB $slice
operator: https://docs.mongodb.org/manual/reference/operator/projection/slice/#slice-projection
Mongoose has a helper function to achieve this: http://mongoosejs.com/docs/api.html#query_Query-slice
So, your example become something like that:
UserModel
.findById(user._id)
.slice('activities', 20)
.select('activities')
.lean()
.exec((err,user)=>{....})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With