How to pass a session to 'Model.create()' in Mongoose.?
Asked Answered
F

2

5

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();
     }


     };
Furry answered 30/10, 2019 at 7:6 Comment(0)
L
8

https://mongoosejs.com/docs/transactions.html

Keep the object in Array, and session as second argument. refer the link here, this might help.

Luigiluigino answered 14/2, 2020 at 21:18 Comment(0)
K
1

Mongoose is saying that the document(s) you want to create need to be in an array if you want to create them as part of a session.

In your example, you would want to do the following:

await Address.create([address], { session });
await Company.create([company], { session });

Note that address and company are now the lone item in an array. If you wanted to create multiple addresses or companies in one line, you could add them to these arrays.

Kenaz answered 30/8 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.