我有一个控制器功能,它成功地用一组联系人更新我的组文档,但问题是如果我向数据库添加另一个联系人,它会覆盖旧联系人,所以我的文档最多只能有 1 个联系人一次。有没有办法在我更新时添加新联系人而不是替换现有联系人?
这是我的控制器功能
const createContact = async (req,res) => {
const { phone_number,country,phone_type,group,firstName,lastName,company,email} = req.body
// we have success gotten group._id and made it into an object
const newContact = new Contact({
//[ // group array of objects
// {
// contacts: [],// _id: '60d2d43345f1de1135185efe',// title: 'vacant',// created: '2021-07-27T19:40:01.600Z'
// },// {
// contacts: [],// _id: '60ff432fa2f369134d838e3c',// title: 'yellow belts',// created: '2021-07-26T23:20:15.933Z'
// }
//]
phone_number: phone_number,country: country,group: group,// this group coming in is an array of objects,each object has array of contacts
phone_type: phone_type,firstName: firstName,lastName: lastName,company: company,email: email,_user: req.user.id
})
const createdContact = await newContact.save() // I now have acces to this objectId
console.log(createdContact._id) // we need to push this into each groups contact array
const GroupId = group.map(groups => groups._id)
const ChosenGroups = await (await Group.updateMany({ '_id': { $in: GroupId}},{$set: {contacts : createdContact._id}}));
console.log(ChosenGroups)
res.status(201).json(createdContact)
}```