Home > Enterprise >  I want to make a collection for cash register,whenever the company collection is inserted cash regis
I want to make a collection for cash register,whenever the company collection is inserted cash regis

Time:11-24

I want to post data in mongodb name company, whenever I post some data using postman, I want another collection name cash register it also stores id of the company(its like storing data in one collection and also store its ID in another collection)

CodePudding user response:

first of all you have to use mongoose middelwares, in particular pre-save like this:

companySchema.pre('save', function (next) {
            CASH_REGISTER_MODEL.create({your object here})
        });

this work because before save create the data you want in the second entity. if you want you also can use post save to create second object AFTER saving the first entity.

CodePudding user response:

You could try it this way:

const newCompany = new Company({...req.body});

await newCompany.save();

const newRegister = new Register({ companyId: newCompany._id }); // Assuming your Register schema contains companyId property field

await newRegister.save();

return res.status(200).json({
  success: true,
  successMessage: 'Company has been created successfully',
  company: newCompany,
});
  • Related