Mongoose “Create” method - Is there no callback? (

2019-08-28 03:17发布

I am using mongoose to create a user object on register. This works fine and any errors are returned as expected.

However, I want to log the user on right after they register (so registering logs you on if there are no errors).

I have the following for the register.

register_controller:

$scope.submitRegister = function() {
    AuthenticationService.register(this.details).success(function() {
        $log.debug('/POST to /api/register worked');
    });
}

services.js:

.service('AuthenticationService', function($http, $timeout, $q, $session, $flash) {
    ...
    this.register = function(details) {
        var register = $http.post('/api/register', details);
        register.success(function() {
            console.log("User added fine"); 
        }).error(function() {
            console.log("error!!!");
        });
        return register;
    };
    ...

users.js:

app.post('/api/register', authentication.register);

passport's authenticate.js:

module.exports = {
...
  register: function(req, res){
    var User = require('./controllers/api/login_api');
    User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err){
      if (err) {
        console.log(err);
        return;
      }
      console.log("User added"); 
      return res.send(200);
    });
  },
...

The error is reported back fine, no troubles, but I would have thought it would report something else back (like the created object?) which I could use down the line so my register_controller can have in the success function(object) {... login(object);...}.

Is this a limitation in the .create method or am I missing something obvious?

Thank you.

1条回答
混吃等死
2楼-- · 2019-08-28 03:53

Two things to change in your server code:

passport's authenticate.js:

module.exports = {
...
  register: function(req, res){
    var User = require('./controllers/api/login_api');
    User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err, user){
      if (err) {
        console.log(err);
        return;
      }
      console.log("User added"); 
      return res.send(200, user);
    });
  },
...

I've added user to your callback Mongoose model.create api - return the created object to the CB

And to change the catch in your client:

.service('AuthenticationService', function($http, $timeout, $q, $session, $flash) {
...
this.register = function(details) {
    var register = $http.post('/api/register', details);
    register.success(function(user) {
        console.log(user); 
    }).error(function() {
        console.log("error!!!");
    });
    return register;
};
...

Now you can do with the created user object whatever you need

查看更多
登录 后发表回答