[英]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.