繁体   English   中英

无法在for循环内的findOne()之后为对象属性添加值

[英]Cannot add value to object property after findOne() inside a for-loop

app.get('/calculatePrice', function(req, res) {
  let toyIds = req.query.id,
    qty = req.query.qty,
    totalPrice = 0,
    subtotal = 0,
    result = {"items": [], "totalPrice": totalPrice},
    item = {};

    for (let i = 0; i < toyIds.length; i++) {
        Toy.findOne({id: toyIds[0]}, { id: 1, price: 1, _id: 0 }, function(err, toy) {
        if (toy) {
            item[item] = toy.id; //doesnt work
            item[qty] = qty[0]; //doesnt work
            item[subtotal] = (toy.price * Number(qty[0])); //doesnt work
            totalPrice += item[subtotal]; //doesnt work

        }
    });
    result.items.push(item);
  }
  res.json(result);
});

我正在尝试通过URL“ / calculateprice?id [0] = 1234&qty [0] = 2&id [1] = 1235&qty [1] = 1&id [2] = 1236&qty [2]提供的各自的ToyId查找mongodb中的特定玩具。 = 5“。

但是,找到它之后,我似乎无法使用数据为我的“ item”对象属性添加值。

我已经做过一些研究,我猜想这与Toy.findOne异步有关,但我真的不理解,似乎自己也找不到解决方案。 对于新手学习节点/ mongodb的帮助和解释将不胜感激!

您可以将循环+ findOne替换为find ,然后需要在回调中移动res.json(result)以使其在异步过程完成后运行:

app.get('/calculatePrice', function(req, res) {
    let toyIds = req.query.id;
    let result = { items: [] };
    Toy.find({id: {$in: toyIds}}, function(err, toys) {
        if(err) {
            res.status(500).json({error: true});
        }
        if (toys) {
            // process the result
            // push toys data to result.items
        }
        res.json(result);
    });
});

暂无
暂无

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

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