How to save multiple items in mongodb using node js

Viewed 57

I'm trying to add multiple list in mongodb, but here i'm getting error called .insert(roles) is not a function.i don't understand the issue here thanks in advance

schema:-

module.exports = mongoose => {
const Role = mongoose.model(
  "role",
  mongoose.Schema(
    {
     roleType : [{ type:String }] 
    }
  )
);
return Role;
};

api call:-

  exports.addRoleFields = ( req , res ) => {
      const {  role } = req.body
      const roles =  new Role([{ roleType:  role }]);
      roles
       .insert(roles)
       .then(data => {
         res.status(200).send({data,statusCode:"200"});
       })
       .catch(err => {
         res.status(500).send({
          message: err.message || "Some error occurred while creating.",
          statusCode:"500"
      });
    })
   })    
  }

here is the postman: enter image description here

1 Answers

Try this:

exports.addRoleFields = (req, res) => {
    const roles = req.body; // const { role } assignment wasn't correct
 
    Role
        .insertMany(roles)
        .then(data => {
            res.status(200).send({ data, statusCode: "200" });
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while creating.",
                statusCode: "500"
            });
        })
})    
}
Related