[英]Issue with Mongoose model.save callback
I am learning Node.js with a book.我正在用一本书学习 Node.js。 Instead of coping and using the book sample code as it is I am using the basis and reusing in own code used as learning exercise.我没有按照原样处理和使用书中的示例代码,而是使用基础并在自己的代码中重用用作学习练习。
I have this code for a new user creation, I will copy what I believe are the relevant.我有这个用于创建新用户的代码,我将复制我认为相关的内容。 What I expect to happen is that user.register uses model.register and receive a true or false depending if the user was created or not and sending a response accordly我期望发生的是 user.register 使用 model.register 并根据用户是否创建并相应地发送响应来接收真或假
app.js capture the post app.js 捕获帖子
app.post('/user', users.actions.register);
user.js register user.js 注册
var register = function ( req, res ) {
if ( req.body.username === '' ||
req.body.email === '' ||
req.body.password === '' ) {
//Some field is blank - insufficient information
console.log('User creation failure: Insufficient data');
res.json(400);
} else {
var newUser = new models.account.user ({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
models.account.register ( newUser, function (succ) {
console.log (succ);
if ( succ === true ) {
res.json(200);
} else {
res.json(400);
}
});
}
};
then account.register然后 account.register
var register = function ( newUser ) {
console.log ('Save command sent.');
newUser.save ( function ( err ) {
if (err) {
console.log(err);
return false;
}
console.log('User Created');
return true;
});
};
The user gets created on the database, and the output on the console is用户在数据库上创建,控制台上的输出是
Save command sent.
User Created
What I was expecting to happen is that succ receives true or false, but I am doing something wrong and cant figure out why.我期待发生的是 succ 接收真或假,但我做错了什么,无法弄清楚为什么。
I made this code works changing the approach, but since this is a learning experiment for me I wanted to be able to do it this way.我让这段代码改变了方法,但由于这对我来说是一个学习实验,我希望能够以这种方式做到这一点。
I would appreciate if someone could point me in the right direction or show me what I am doing wrong.如果有人能指出我正确的方向或告诉我我做错了什么,我将不胜感激。 Thanks.谢谢。
models.account.register ( newUser, function (succ) {
...
}
you are passing an anonymous function as the second parameter to register
.您将匿名函数作为第二个参数传递给register
。 So, register
has to accept that and invoke it with the results, like this所以, register
必须接受它并用结果调用它,就像这样
var register = function ( newUser, callBackFunction ) { // accept the callback
console.log ('Save command sent.');
newUser.save ( function ( err ) {
if (err) {
console.log(err);
return callBackFunction(false); // invoke it on failure :(
}
console.log('User Created');
return callBackFunction(true); // invoke it on Success :)
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.