【问题标题】:How do I assign a created contact to the current user in Mongoose?如何将创建的联系人分配给 Mongoose 中的当前用户?
【发布时间】:2018-08-04 14:50:57
【问题描述】:

我正在尝试创建一个推送到当前用户的联系人数组的联系人。

我的控制器目前只创建一个一般性的联系人,而不是特定于用户。

控制器:

function contactsCreate(req, res) {

  Contact
    .create(req.body)
    .then(contact => res.status(201).json(contact))
    .catch(() => res.status(500).json({ message: 'Something went wrong'}));
}

联系模特:

const contactSchema = new Schema({

  firstName: String,
  lastName: String,
  email: String,
  job: String,
  address: String,
  number: Number
});

用户模型:

const userSchema = new mongoose.Schema({

  username: { type: String, unique: true, required: true },
  email: { type: String, unique: true, required: true },
  passwordHash: { type: String, required: true },
  contacts: [{ type: mongoose.Schema.ObjectId, ref: 'Contact' }]
});

【问题讨论】:

  • 这取决于您如何进行身份验证。您是否可以访问护照中请求的用户信息?
  • 我相信是的,我使用的是 express-jwt 和 bcrypt

标签: javascript node.js express mongoose mean-stack


【解决方案1】:

假设您可以访问请求对象上的用户名,这样的事情应该可以工作:

async function contactsCreate(req, res) {
  const username = request.User.username

  try {
      const newContact = await Contact.create(req.body)
      const user = await User.findOne({username})
      user.contacts.push(newContact)
      await user.save()
      return res.status(201).json(contact)
  } catch ( err ) {
      return res.status(500).json({ message: 'Something went wrong'})
  }
}

【讨论】:

  • 非常感谢,我在下面稍微调整了你的答案
【解决方案2】:

感谢上面的 LazyElephant。解决方案(调整)是:

async function contactsCreate(req, res) {
  const userId = req.user.id;

  try {
    const newContact = await Contact.create(req.body);
    const user = await User.findById(userId);
    user.contacts.push(newContact);
    await user.save();
    return res.status(201).json(newContact);
  } catch ( err ) {
    return res.status(500).json({ message: 'Something went wrong'});
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-05
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多