考虑下面的代码:
userSessionDetail.save((err, data) => {
if (data) {
console.log('User Session has been successfully created!');
returnUserData = {
username: user.username,
sessionid: LoginUserModel.findOne({
email: req.body._usercredentials.email
})
.sort({
loginDateTime: 'desc'
})
.then((res) => {
// console.log(res._id) Successfully get value from promise
return res._id
})
.catch((err) => {
console.log(err);
})
}
console.log(returnUserData.sessionid); //empty
} else {
console.log('While creating User Session, something went wrong.');
}
})
我正在尝试的是从我的承诺中获取价值并将我的财产价值sessionid
加入。
上面的代码并没有从我的承诺中获得价值。它显示了我的结果:
用户会话已成功创建!承诺{发射器:
EventEmitter { domain:null, _events:{reject:[Function]}, _eventsCount:1, _maxListeners:undefined},emit:{},ends:true}
您是否可以澄清如何将生成的'res._id'传递给属性sessionid的值,而不是承诺本身?
答案 0 :(得分:1)
mongoose的findone方法返回一个promise,当mongodb(最终)返回数据时执行Promise.then()
回调:
userSessionDetail.save((err, data) => {
if (data) {
console.log('User Session has been successfully created!');
LoginUserModel.findOne({
email: req.body._usercredentials.email
})
.sort({
loginDateTime: 'desc'
})
.then((res) => {
// console.log(res._id) Successfully get value from promise
returnUserData = {
username: user.username,
sessionid: res._id
}
console.log(returnUserData.sessionid); //empty
})
.catch((err) => {
console.log(err);
})
} else {
console.log('While creating User Session, something went wrong.');
}
})