How can I pass a session variable to Model.Create() in mongoose.
I have tried some code but it gives me the following error: "to pass a session
to Model.create()
in Mongoose, you must pass an array".
const mongoose = require("mongoose");
const Company = require("../models/company");
const Address = require("../models/userAddress");
exports.add_company = async (req ,res,next)=>{
const session = await mongoose.startSession();
await session.startTransaction();
const createdDocs = [];
try{
const address = new Address({
_id: new mongoose.Types.ObjectId(),
addressName: req.body.addressName,
address1: req.body.address1,
address2: req.body.address2,
city: req.body.city,
pincode: req.body.pincode
});
await Address.create(session,address);
createdDocs.push(address);
const company = new Company({
_id: new mongoose.Types.ObjectId(),
companyName: req.body.companyname,
companyType: req.body.companytype,
companyDesc: req.body.companydesc,
companyWebsite: req.body.companywebsite,
companyLogo: req.file ? req.file.path : null,
addressId:createdDocs[0].addressId
});
await Company.create(session,company);
createdDocs.push(company);
await session.commitTransaction();
console.log(createdDocs);
res.status(200).json({
message:"company registered registerd",
companyName:createdDocs[1].companyName,
address:createdDocs[0].addressName,
});
}
catch(err){
await session.abortTransaction();
res.json({ status:false, message:err.message});
}
finally {
session.endSession();
}
};