【问题标题】:Get or create user with Mongoose og promises使用 Mongoose og Promise 获取或创建用户
【发布时间】:2018-02-16 11:53:47
【问题描述】:

如何提供用户名和密码并检查用户是否已存在,如果不存在,我想创建用户。所以它基本上应该是一个get或create函数。

我认为可能是这样的

const username = 'username';
const password = 'password';

User.findOne({ username }).then(existingUser => {
  if (!existingUser) {
    return User.create({ username, password }).then(newUser => {
      return newUser;
    }).catch(console.error);
  }

  existingUser.comparePassword(password, (err, isMatch) => {
    if (!isMatch) { return null; }

    return existingUser;
  });
}).catch(console.error);

问题是我完全理解如何构建承诺。

我想我应该只有 1 个 catch 而不是本例中的 2 个。

那么,我该如何构建这样的结构,以便始终返回用户(无论是现有用户还是新用户)或 null

【问题讨论】:

    标签: node.js mongoose promise


    【解决方案1】:

    我想我应该只有 1 个 catch 而不是本例中的 2 个。

    是的,你应该这样做。

    那么,我该如何构造它,让我始终返回用户(无论是现有用户还是新用户)或 null?

    您可以使用以下解决方案:

    const username = 'username';
    const password = 'password';
    
    User
      .findOne({ username })
      .then(existingUser => {
        if (!existingUser) {
          return User.create({ username, password });
        }
        return new Promise((resolve, reject) => existingUser.comparePassword(password, (err, isMatch) => {
          if (!isMatch) {
            return reject(new Error('Incorrect password'));
          }
          resolve(user);
        });
      })
      .catch(console.error);
    

    【讨论】:

    • 谢谢!如果existingUser.comparePassword 也是一个承诺而不是使用回调函数怎么办?我能以某种方式摆脱new Promise((res, rej) => ...)吗?
    • 如果existingUser.comparePassword返回一个promise,你不应该在这里使用promise构造函数,因为它是explicit promise construction antipattern
    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2016-06-22
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多