如何将创建的联系人分配给 Mongoose 中的当前用户?

How do I assign a created contact to the current user in Mongoose?

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

我的控制器目前只创建一个通用的联系人,并不特定于用户。

控制器:

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' }]
});

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

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'})
  }
}

感谢上面的 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'});
  }
}