Reputation: 93
I am having a tough time trying to execute a slice on an array
I have a collection called comments, each document has an array field, i want to access it and apply slice for paging purpose please help !! tried monk
and mongodb
no good
Example:
{
_id:xyz,
msgs:[{.....},{.....},{.....}]
}
database.collection("comments")
.find({"_id": id},{ "msgs": { "$slice": [2,5] } })
.toArray( function(err, result){
//implementation
});
Upvotes: 1
Views: 1283
Reputation: 22276
From the node-js mongo driver docs:
2.x syntax:
const cursor = coll.find({ a: 42 }, { someField: 1 });
3.x syntax:
const cursor = coll.find({ a: 42 }).project({ someField: 1 });
/* OR */
`const cursor = coll.find({ a: 42 }, { projection: { someField: 1 } });`
Basically node-js mongo driver version upgrade from 2.x to 3.x had several "breaking" changes including the projection in a query.
Upvotes: 0
Reputation: 856
For mongodb
Driver:
Instead of
.find({"_id": id},{ "msgs": { "$slice": [2,5] } })
Use
.find({"_id": id}).project({ "msgs": { "$slice": [2,5] } })
As given here the $slice
operator is of Projection type.
The mongodb
driver for NodeJS needs call to an extra .project
function to project selective fields as well as to use projection operators.
Upvotes: 6