findIndex没有返回正确的索引

时间:2017-03-10 02:12:04

标签: javascript arrays node.js express mongoose

findeIndex未在快速路由器功能中返回正确的索引。

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文件中测试了它并且它工作得很好,我不知道为什么它没有'在这里工作。

1 个答案:

答案 0 :(得分:0)

问题在于mongoose,显然它返回对象值而不是字符串值。所以答案是:

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();
}));