2

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

2
  • Try with roles.save instead of roles.insert Commented Jul 8, 2021 at 14:37
  • i tried , but getting the same issue roles.insert is not a function Commented Jul 8, 2021 at 15:17

1 Answer 1

1

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"
            });
        })
})    
}
Sign up to request clarification or add additional context in comments.

4 Comments

this is the response i'm getting { "data": [ { "roleType": [], "_id": "60e71699c48770200c629158", "__v": 0 } ], "statusCode": "200" }
Don't you see the created documents in the database?
Oh alright, I know the problem. Please check my answer again I updated it
it is showing the data, thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.