Mongoose Slice error - Exercise Tracker

Tell us what’s happening:
I am trying to use slice() to limit my exercises array based on the limit query string, and I believe I am following the correct syntax, but I get this error:
Invalid $slice syntax. The given syntax { $slice: “5” } did not match the find() syntax because :: Location31273: $slice only supports numbers and [skip, limit] arrays :: The given syntax did not match the expression $slice syntax. :: caused by :: Expression $slice takes at least 2 arguments, and at most 3, but 1 were passed in.

Here is the line of code where I am clearly passing in 2 arguments- ‘exercises’ and the limit.
User.findOne({_id: req.params._id}).slice(‘exercises’,limit).exec(function(err, data){

Your project link(s)

solution: boilerplate-project-exercisetracker - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

let limit = req.query.limit;

In the above code in your Replit, the variable limit is of type string. The slice() method in your following code is expecting a number. That might be the cause of the error.

User.findOne({_id: req.params._id})
    .slice(‘exercises’, limit)
    .exec(function(err, data) { 
              //...
});

I don’t think so because I also tried with hard coding a number 5 instead of using the limit variable. Any other suggestion?

Please post the error you are getting when you use the slice with a number. Also, post the complete command you are working with.

I had tried the following syntax, and they both work fine.

let limit = 2;
User.findOne({ _id: "some id"}, { exercises: { $slice: limit }}, function(err, data) {
	if (err) throw err;
	console.log(data);
});

User.findOne({ _id: "some id"}).slice('exercises', limit).exec( function(err, data) {
	if (err) throw err;
	console.log(data);
});
1 Like

That solved it, thank you so much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.