Search code examples
javascriptmongodbexpressmongoose-schema

Cannot post ref id to parrent collection mongoDB


Im trying to insert two records into mongoDB. One as a new collection the other a ref id.

Sample of schema Company{ name: Acme Company, Locations: [refID] }

the id & location payload will be sent in the body of the request.

addNewLocation: (req, res) => {
        
        let {id, ...payload} = req.body;
        
        db.Location.create(payload)
            .then( record => {
                let refId = record._id
                db.Company.findOneAndUpdate( {_id: id} , { $push: { locations: refId } }, { new: true })
            })
            .then( result => {
                res.status(201).json({success: true},{result})
            })
            .catch( err => {
                res.status(422).json({success: false},{err})
            })
    }

when viewing the update (on Robo3T) it appears to be inserting a document into the location, but it doesn't insert the ref id in the companies collection. Any ideas what might be causing this?


Solution

  • createNewLocation: (req, res) => {
        let { companyId , ...payload } = req.body;
    
        db.Location.create(payload)
        .then(({_id}) => {
           return db.Company.findOneAndUpdate(companyId, {$push:{location: _id}},{new: true})
        })
        .then(()=>{
            res.status(201).json({success: true})
        })
        .catch((err)=>{
            res.status(422).json({success: false})
        })
    }
    

    Here is the solution, just needed a return.