Prakash Kumar
Prakash Kumar

Reputation: 879

Mongoose query in array for retrieving elements starting from index 0 to n where n is the position of the element from the last

I want to return all elements of my array which appear before a particular position in the array from the last, for example see below example.

var arr = [59, 34, 6, 9, 45, 67, 89, 56, 34, 26, 56, 45] now for position = 5 which means 5th position from the last which is 56 i want to get array [56, 89, 67, 45, 9, 6, 34, 59]

Mongoose Schema

var user_coupons_schema = new Schema({
mobile_no: {type: String, unique: true},
coupons: [{type: String}]
});

Mongoose query

usercoupons.findOne({mobile_no: mobile_no}, {'_id':0, coupons: { "$slice": [-skip, limit]}}, function(err, docs) {

Update

Using Aggregation my code is given below but can someone please tell me why below value is coming NaN inside $slice

"arr_size" - skip -> NaN

usercoupons.aggregate(
        { $match : {mobile_no: mobile_no} },
        { $project: {arr_size: {$size: "$coupons"}} },
        { $project: {_id:0, coupons: { "$slice": [0, "arr_size" - skip]}} },
        function(err, docs) {
            if (err) {
                console.log('Hii1');
            } else {
                if (docs) {
                    console.log('Hii2');
                } else {
                    console.log('Hii3');
                }
            }
        }
    );

Upvotes: 0

Views: 1195

Answers (1)

Kairat
Kairat

Reputation: 800

I'm going to assume you simply have a JavaScript array based on your comment.

var arr = [59, 34, 6, 9, 45, 67, 89, 56, 34, 26, 56, 45];
var ind = 5;
var subset = arr.slice(0, arr.length - ind + 1); // if you want to include value at ind'th position from the last
// OR    
var subset = arr.slice(0, arr.length - ind); // if you don't want to include value at ind'th position from the last

Upvotes: 1

Related Questions