简体   繁体   中英

Issue with Mongoose model.save callback

I am learning Node.js with a book. 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

app.js capture the post

app.post('/user', users.actions.register);

user.js register

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

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.

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 . So, register has to accept that and invoke it with the results, like this

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 :)
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM