【问题标题】:How can I update a document in a collection as soon as a new document is created with a reference that particular document in seperate collection?使用单独集合中的特定文档的引用创建新文档后,如何更新集合中的文档?
【发布时间】:2021-07-28 14:31:49
【问题描述】:

我想创建一个新联系人。此联系人将具有如下所示的架构

当我创建这个新联系人时,我将发送一个组、firstName、lastName 和 _user 参考。该组将事先已经创建(请参阅下面的架构),并将其在 ObjectId 上。

所以当我创建这个contactSchema时,我如何能够更新已经创建的GroupSchema,以便它知道这个Contact Schema的这个特定ObjectId现在有一个对GroupSchema的引用......我希望有一个很好的解释

我正在使用 Node.js Express 和 MongoDB

const contactSchema = new Schema({
  
    group: [{
        type: Schema.Types.ObjectId, ref: 'group', 
        required: [true, 'Group must not be empty']
    }],
    firstName: String,
    lastName: String, 
    
    
    _user: {type: Schema.Types.ObjectId, ref: 'User' },

GroupSchema(这将已经创建)

const mongoose = require ('mongoose')
const { Schema } = mongoose;

const groupSchema = new Schema ({
    title: String,
    created: {
        type: Date,
        default: Date.now
    },
    contacts: [{type: Schema.Types.ObjectId, ref: 'contact' }],
    _user: {type: Schema.Types.ObjectId, ref: 'User' },
    
})

module.exports = mongoose.model('group', groupSchema)

这是我当前用于创建新联系人的控制器功能, 我可以在这个控制器函数中添加逻辑吗?

const createContact = async (req, res) => {
                const { phone_number, country, phone_type, group, firstName, lastName, company, email} = req.body
                const newContact = new Contact({
                    phone_number: phone_number,
                    country: country,
                    group: group,
                    phone_type: phone_type,
                    firstName: firstName,
                    lastName: lastName,
                    company: company,
                    email: email,
                    _user: req.user.id
                })
                const createdContact = await newContact.save()
                res.status(201).json(createdContact)
            }

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我决定发布我找到的这个解决方案,一旦我更聪明,我会更新这个......

    下面是我的控制器功能

         const createContact = async (req, res) => {
                    const { group, firstName, lastName, company, email} = req.body
     
    
                    const newContact = new Contact({
                                                                              
                           //[    // group array of objects as they come in from above
                          //  {
                         //    contacts: [],
                         //    _id: '60d2d',
                        //    title: 'vacant',
                        //    created: '2021-07-27'
                        //  },
                        //  {
                       //    contacts: [],
                       //    _id: '60ff4',
                       //    title: 'yellow belts',
                       //    created: '2021-07-26'
                        //  }
                         //]
                       
                        group: group, // this group coming in is an array of objects, each object has array of contacts
                        firstName: firstName,
                        lastName: lastName,
                        company: company,
                        email: email,
                        _user: req.user.id
                    })
                    const createdContact = await newContact.save() // I now have access to this newly created objectId
                    console.log(createdContact._id) // we need to push this into each groups contact array
                    const GroupId = group.map(groups =>  groups._id) // map over groups array to get the objectIds so we can query the Groups collection by id
                    const ChosenGroups = await (await Group.updateMany({ '_id': { $in: GroupId}}, {$set: {contacts : createdContact._id}}));
                    console.log(ChosenGroups)
                  
               
                    res.status(201).json(createdContact)
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2018-01-09
      • 1970-01-01
      • 2019-09-18
      • 2020-08-25
      • 2021-05-12
      相关资源
      最近更新 更多