我已经在node.js项目中定义了分层。
结构如下所示
user.service.js
user.controller.js
Service
从Controller
中被调用,在Service
内部,mongoose findOneAndUpdate
被调用。
现在,我想在更新后从Service
返回自定义对象,但是result
对象始终在Controller
中未定义
user.service.js
async function activate(tokenParam)
{
await User.findOneAndUpdate(
{
activationToken: tokenParam
},
{
$set:{isActive:true}
},
{
new: true,
useFindAndModify: false
})
.exec()
.then(function (err, doc) {
var result = new Result();
if (err)
{
result.hasData = false;
result.exception = err
}
else
{
result.hasData = true;
result.data = doc.isActive
}
console.log("User Service: Result: " + result)
return result;
});
}
user.controller.js
userService
.activate(req.params.token)
.then(result => {
console.log("User Controller: Activate:" + result);
if (result && result.hasData && result.data) {
res.status(200).json(result); //Account Activated
} else {
res.status(401).json(result); //Account Not Activated
}
})
.catch(err => next(err));
预期产量
//console.log("User Service: Result: " + result)
User Service: Result: { ... }
//console.log("User Controller: Activate:" +result)
User Controller: Activate: Result: { ... }
实际输出
//console.log("User Service: Result: " + result)
User Service: Result: { ... }
//console.log("User Controller: Activate:" +result)
User Controller: Activate: undefined
有什么想法吗?
答案 0 :(得分:1)
更改您的user.service.js。
async function activate(tokenParam)
{
let result = new Result();
try {
const user = await User.findOneAndUpdate({
activationToken: tokenParam
},
{
$set:{isActive:true}
},
{
new: true,
useFindAndModify: false
})
if(user) {
result.hasData = true;
result.data = doc.isActive
return result;
}
} catch(err){
result.hasData = false;
result.exception = err;
return result;
}
}
答案 1 :(得分:1)
async function activate(tokenParam)
{
var result = new Result();
try{
var doc = await User.findOneAndUpdate(
{
activationToken: tokenParam
},
{
$set:{isActive:true}
},
{
new: true,
useFindAndModify: false
})
result.hasData = true;
result.data = doc.isActive
}
catch(err)
{
result.hasData = false;
result.exception = err
}
console.log("User Service: Result: " + result)
return new Promise((resolve, reject)=>{
resolve(result)
});
}
在处理错误情况时,不存在拒绝。另外,如果您想使用拒绝查看发生什么错误,请在函数作用域内创建一个新变量,并在catch内设置为err。