【发布时间】:2017-10-10 05:00:30
【问题描述】:
我遇到了从 MongoDB 的 mLab 返回的 Promise 的问题。部分数据正确传递,其余未定义。我不确定这里发生了什么。
这是我连接到的 mLab 集合中的 JSON 对象。
{
"_id": {
"$oid": "591424da932aad14186a7213"
},
"name": "Archos Elements 50 Oxygen",
"weight_oz": 4.59,
"battery_capacity_mAh": 2300,
"platform": "Android",
"date": {
"$date": "2017-05-11T08:46:18.684Z"
},
"dimensions": {
"width_mm": 70.5,
"height_mm": 143,
"depth_mm": 9.9
},
"__v": 0
}
这就是我检索数据的方式(body-parser 用于捕获用户通过 HTML 表单输入的手机的“名称”)
router.post('/page_2', function(req, res){
phone = req.body.phone
mobile_and_tablet_model.find({name:phone}).exec(function(err, result) {
if (err)
throw err;
}).then(function(MongoDBdata){
console.log(MongoDBdata[0]) // logs out entire JSON object correctly
console.log(MongoDBdata[0]._id) // 5002
console.log(MongoDBdata[0].name) // Archos Elements 50 Oxygen
console.log(MongoDBdata[0].weight_oz) // undefined
console.log(MongoDBdata[0].battery_capacity_mAh) // undefined
console.log(MongoDBdata[0].platform) // Android
console.log(MongoDBdata[0].date) // 2017-05-11T08:06:27.894Z
console.log(MongoDBdata[0].dimensions) // undefined
res.render('page_2.hbs', {
title: 'some title',
phone: phone,
battery_capacity: MongoDBdata[0].battery_capacity_mAh, // undefined
platform: MongoDBdata[0].platform // Android
})
})
})
有人可以帮助我理解这种行为并帮助我解决它吗?
我不明白为什么 JSON 对象上的某些嵌套值会出现“未定义”。我远不是 Promises 方面的专家,但如果我理解正确,那么 Promise 已经解决,所以同步/异步行为不应该在这里发挥作用吗? (特别是因为 console.log(MongoDBdata[0]) 完全注销了 JSON 内容)。
非常感谢!
【问题讨论】:
-
你为什么同时使用
exec()中的回调和只使用其中一个的承诺?exec()返回一个承诺,以便您可以使用.catch(function(error){ //do whaterver you want with this error });处理错误 -
感谢@mJehanno 的评论。我相应地调整了代码。完全有道理。不幸的是,问题仍然存在。
标签: json node.js mongodb asynchronous mongoose