javascript - 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 中返回信息。有什么建议吗?泰。
解决方案
推荐阅读
- clojure - Clojure 使用 Java JsonPath
- javascript - Highcharts JS v4.0.4 中的图表未完全加载
- amcharts - AmChart 未出现在 md 对话框中
- php - 使用开始日期 PHP 每周返回结果
- google-chrome - Opensearch - 更改搜索引擎的名称
- keras - 使用 Keras 进行预测。我不断收到错误消息
- rabbitmq - SSH、RabbitMQ、协议“inet_tcp”:注册/监听错误:econnrefused
- .net - CultureInfo.GetCultures 为特定文化返回不同的 DateTimeSettings,而不是按名称或 LCID 使用 GetCultureInfo
- html.textboxfor - 想知道C#.Dot net MVC Helper Class css文件位置
- asp.net - 如何在本地使用 sharePoint 做一个公共站点