【发布时间】:2018-03-13 11:30:18
【问题描述】:
我正在使用 promise 从 DB 中获取一个值,并且我想在 db 中搜索表单提交后检索到的值 (req.body.country),获取其 id 并将其分配给声明的变量承诺,如何获得? 代码如下:
var newAddress = new Address(); // Address is a mongoose model.
newAddress.city = req.body.city;
newAddress.state = req.body.state;
Country
.findOne({name: req.body.country})
.then(function (result) {
newAddress.country = result;
})
.catch(function(err) {
res.send(500, {message: 'Failed to search into DB'});
});
newAddress.save(function (err, result) {
if(err) {
res.status(500).send('Failed to save the newAddress to DB: ' + err);
}
});
这是猫鼬地址模型:
var addressSchema = new Schema({
street1: {type: String, required: true},
street2: String,
city: String,
state: String,
zip: String,
country: {type: Schema.Types.ObjectId, ref: 'Country'},
lat: String,
long: String
});
一切都在嵌套回调中,我正在尝试从回调转移到 Promise。 我没有错误,它根本不会将国家/地区保存在地址中,因为承诺中的 newAddress 与代码开头声明的 newAddress 不同
【问题讨论】:
标签: node.js mongodb mongoose promise