首页 > 解决方案 > Mongo 未定义的响应

问题描述

我有这个模式(Cart),它可以有一个产品数组,并且产品有两个重要的字段,一个是_id另一个是sellPrice

let cartSchema = new Schema({
    ...
    products: [{
        _id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product',
            required: [true, '{PATH} required']
        },
        cant: {
            type: Number,
            required: [true, '{PATH} required'],
            default: 1
        },
        sellPrice: {
            type: Number
        }
    }],
    ...
});

当我想将购物车添加到数据库时,我使用此功能:

let addCart = (req, res) => {
    let body = req.body;
    let cart = new Cart({
        ...
        products: body.products,
        ...
    });
    cart.products.forEach(product => {
        let id = product._id;
        let productObt = Product.findById(id)
        .exec((err, productDB) => {
            if (err) {
                return false;
            }
            if (!productDB) {
                return false;
            }
            console.log(productDB);
            product.sellPrice = productDB.sellPrice;
            return productDB;
        });
        console.log(productObt);
    });
    console.log(cart); // this cart is wrong, this show: 
    //products: [
    //    { cant: 1, _id: 5fa00779e8c8633bd00dc9c5 },
    //    { cant: 1, _id: 5fa006dde8c8633bd00dc9c0 }
    //],
    //without sellPrice
    cart.save((err, cartDB) => {
        if (err) {
            res.status(400).json({
                ok: false,
                error: err
            })
        }
        res.json({
            ok: true,
            cart: cartDB._id
        })
    });
}

我在 forEach 上尝试做的是,对于阵列中的每个产品,在数据库中的文档中获取他的 sellPrice,这样我就可以将此价格添加到数据库中cart.products[].sellPrice并将其保存到数据库中。但是console.log(productObt);返回 null 而console.log(productDB);不是。

我认为是因为.exec是异步的,我需要更好地使用回调,但我对 NodeJS 和 JS 有点陌生,所以我不知道如何在 productDB 中返回信息。有什么建议吗?泰。

标签: javascriptnode.jsmongodb

解决方案


推荐阅读