2017-03-10 68 views
0

findeIndex在快速路由器函數中未返回正確的索引。findIndex未返回正確的索引

module.exports.nearestOffices = (req, res, next) => { 
    Order.findById(req.params.idOrder).exec() 
    .then(order => { 
     return Promise.all([ 
     Promise.resolve(order), 
     Office.find({'location': {$near: order.address_deliver.location, $maxDistance: maxDistance}}).sort({'timeToFinish': -1}).exec() 
     ]); 
    }) 
    .then(rslts => { 
     let order = rslts[0]; 
     let offices = rslts[1]; 

     console.log('findIdex test: ', offices[0].stockProducts.findIndex(o => { 
     console.log(o.product, '===', order.products[1].product); 
     return o.product === order.products[1].product; 
     })); 

     return Promise.resolve('message'); 
    }) 
    .then(rslt => res.json(rslt)) 
    .catch(err => next(err)); 
} 

變量的內容訂購和辦公室是:

//offices 
[ 
{ 
    "stockProducts": [ 
    { 
    "product": "58c1a7f62193b95eec1765ad", 
    "_id": "58c1a7f72193b95eec1765ae", 
    "stock": 3 
    }, 
    { 
    "product": "58c1a8212193b95eec1765af", 
    "_id": "58c1a8212193b95eec1765b0", 
    "stock": 15 
    }, 
    { 
    "product": "58c1a84a2193b95eec1765b1", 
    "_id": "58c1a84a2193b95eec1765b2", 
    "stock": 20 
    }, 
    { 
    "product": "58c1a85f2193b95eec1765b3", 
    "_id": "58c1a85f2193b95eec1765b4", 
    "stock": 10 
    } 
    ] 
} 
]; 

//order 
{ 
"products": [ 
    { 
    "product": "58c1a84a2193b95eec1765b1", 
    "price": 2, 
    "cant": 5, 
    "_id": "58c1c0e57b32c431d99a3969" 
    }, 
    { 
    "product": "58c1a8212193b95eec1765af", 
    "price": 6, 
    "cant": 2, 
    "_id": "58c1c1107b32c431d99a396a" 
    } 
] 
}; 

所述的console.log的輸出是:

58c1a7f62193b95eec1765ad '===' 58c1a8212193b95eec1765af 
58c1a8212193b95eec1765af '===' 58c1a8212193b95eec1765af 
58c1a84a2193b95eec1765b1 '===' 58c1a8212193b95eec1765af 
58c1a85f2193b95eec1765b3 '===' 58c1a8212193b95eec1765af 

findIdex test: -1 

它應具有在第二行返回1,但我不知道爲什麼它沒有,我在另一個沒有函數的js文件中測試了它,它工作得很好,我不知道爲什麼它不起作用。

+0

鑑於您使用過'===','typeof o.product'和'typeof order.products [1] .product'是什麼? – Bergi

+0

@Bergi他們都是字符串。我也嘗試過==,它也不起作用,我一直在這樣的3個小時。 – yosiprompt

+2

也許有一些白色空間或什麼的,嘗試修剪它 –

回答

0

問題在於貓鼬,顯然它返回的對象值不是字符串值。所以答案是:

console.log('findIdex test: ', offices[0].stockProducts.findIndex(o => { 
    console.log(o.product.toString(), '===', order.products[1].product.toString()); 
    return o.product.toString() === order.products[1].product.toString(); 
}));