繁体   English   中英

数组中的猫鼬查询,用于检索从索引0到n的元素,其中n是最后一个元素的位置

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

我想返回数组的所有元素,这些元素从最后一个出现在数组的特定位置之前,例如,请参见下面的示例。

var arr = [59,34,6,9,45,67,89,56,34,26,56,45]现在位置= 5,这意味着从最后一个是56的第五个位置,我想获取数组[56 ,89,67,45,9,6,34,59]

猫鼬模式

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

猫鼬查询

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

更新资料

使用聚合我的代码在下面给出,但是有人可以告诉我为什么下面的值在$ slice中变成NaN

“ arr_size”-跳过-> 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');
                }
            }
        }
    );

我将假设您只是基于您的注释的JavaScript数组。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM