我正在尝试创建一个推送到当前用户的联系人数组的联系人。
我的控制器目前只创建一个通用的联系人,并不是特定于用户。
控制器:
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' }]
});
答案 0 :(得分:0)
假设您可以访问请求对象上的用户名,那么这样的事情应该有效:
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'})
}
}
答案 1 :(得分:0)
感谢上面的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'});
}
}