开发者问题收集

Sails.JS-创建用户不会返回用户对象

2017-09-04
1457

我的 Sails 1.0 应用程序中有一个函数,它将新用户添加到 MongoDB,然后在最后以 JSON 形式返回 User 对象...

User 确实被添加到集合中,但在尝试获取新 User 对象的 _id 时会引发错误。当我尝试 console.log() createdUser 时,它返回 Undefined。试图弄清楚如何在 Mongo 中创建用户,但不在同一函数中将其作为对象返回?

简而言之,Register() 函数执行以下操作:

  • 验证某些输入
  • 检查电子邮件地址是否有效
  • 加密密码
  • 查找 Gravatar URL(如果适用)
  • 将用户插入集合
  • 在 req.session 中设置 user._id(此处发生错误)
  • 以 JSON 形式返回用户对象

错误:

info: ·• Auto-migrating...  (alter)
info:    Hold tight, this could take a moment.
info:  ✓ Auto-migration complete.

warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v1.0.0-37           |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.

debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)

debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property '_id' of undefined
    at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
    at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
    at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
    at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
    at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
    at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
    at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
    at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
    at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
    at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
                              ^

我尝试将 id 切换为 _id,因为它是 Mongo,但没有成功,当我尝试 console.log createdUser 时,它是未定义的。

记录正在数据库中创建...任何帮助,告诉我我可能在哪里搞砸了将不胜感激。

在此处输入图片描述

我正在使用的完整注册功能:

  register: function (req, res) {

    if (_.isUndefined(req.param('first'))) {
      return res.badRequest('A first name is required!');
    }

    if (_.isUndefined(req.param('last'))) {
      return res.badRequest('A last name is required!');
    }

    if (_.isUndefined(req.param('phone'))) {
      return res.badRequest('A phone number is required!');
    }

    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('An email address is required!');
    }

    if (req.param('email') !== req.param('emailConfirm')) {
      return res.badRequest('Email addresses do not match!');
    }

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    if (req.param('password') !== req.param('confirmPassword')) {
      return res.badRequest('Passwords do not match!');
    }

    if (_.isUndefined(req.param('tos'))) {
      return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
    }



    Emailaddresses.validate({
      string: req.param('email'),
    }).exec({
      // An unexpected error occurred.
      error: function (err) {
        return res.serverError(err);
      },
      // The provided string is not an email address.
      invalid: function () {
        return res.badRequest('Doesn\'t look like an email address to me!');
      },
      // OK.
      success: function () {

        Passwords.encryptPassword({
          password: req.param('password'),
        }).exec({

          error: function (err) {
            return res.serverError(err);
          },

          success: function (result) {

            var options = {};

            // gravitar image for user, if present
            try {

              options.gravatarURL = Gravatar.getImageUrl({
                emailAddress: req.param('email')
              }).execSync();

            } catch (err) {
              return res.serverError(err);
            }

            options.email = req.param('email');
            options.username = req.param('username');
            options.encryptedPassword = result;
            options.deleted = false;
            options.deletedDate = '';
            options.admin = false;
            options.banned = false;
            options.paypalEmail = '';


            // validate that email address has not been used before
            User.find({email: req.param('email')}).exec(function(err, user) {
              if (err) {
                return res.negotiate(err);
              }

              if (user.length > 0) {
                return res.badRequest('Invalid email, this email address is already in use.');
              } else {
                // create new user
                User.create(options).exec(function (err, createdUser) {

                  if (err) {
                    console.log('the error is: ', err.invalidAttributes);
                    return res.negotiate(err);
                  }

                  // Log the user in
                  console.log(createdUser);
                  req.session.userId = createdUser._id;

                  // NOTHING IS BEING RETURNED IN createdUser

                  return res.json(createdUser);
                });

              }
            });

          }
        });
      }
    });
  },
3个回答

从 sails 1.0 开始,您需要指定希望从 create 调用返回该模型。要执行该链,请使用 fetch 调用 create

let createdUser = await User.create({ name: "Some name" }).fetch();

此外,现在 await 比回调更受青睐。

有关此内容的更多信息,请访问: https://next.sailsjs.com/documentation/reference/waterline-orm/models/create

martskins
2017-11-15

这看起来确实很奇怪。但我看到了一个可能的罪魁祸首……当您使用 User.find() 检查电子邮件唯一性时,我无法识别您对 find 的使用。您是这样调用它的:

User.find({email: req.param('email')}, function(err, user) {
    //...
});

但我不认为 find 接受第二个输入。您可能指的是 exec

User.find({email: req.param('email')}).exec(function(err, user) {
    //...
});

我无法理解导致您特定错误的确切逻辑,但如果您以某种方式执行了不应该存在的函数参数,那么修复它是一个开始。

arbuthnott
2017-09-05

我遇到了同样的问题。然后我尝试 findOrCreate,它返回了新记录。我认为这是 Sails 1.0 的一个错误,因为我从未在 0.12 中遇到过这个问题。

Yunfeng
2017-11-09