skip to Main Content

Hii guys I have currently working on a project where I am using mongoose and my I have latest version of 7.0.0.
The issue is that when I am trying to give a callback in Model.insertMany() operation in console its showing that
** MongooseError: Model.insertMany() no longer accepts a callback**

I added my code below. I want that is there any other alternatives to solve this error.

in app.js —-

const express = require("express");
const mongoose = require("mongoose");// require mongoose
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

//create a todolistDB database and connect it
mongoose.connect("mongodb://127.0.0.1/todolistDB", {useNewUrlParser:true});

//create a Schema of only name feild
const itemSchema = new mongoose.Schema({
     name:String
});

const Item = mongoose.model("Item", itemSchema); // create a model of Items

const Item1= new Item({
  name:"Welcome to the todolist"
});

const Item2= new Item({
  name:"Click + button to add items"
});

const Item3= new Item({
  name:"click delete to remove item"
});

const defaultItem= [Item1, Item2, Item3 ]; // create a array of items doc

Item.insertMany(defaultItem,{
  if(err){
    console.log(err);
  }else{
    console.log("Items added succesfully");
  }
});

3

Answers


  1. You should try use await to handle the promise.

    MDN Promise

    Here’s a quick sample of how to use await. You probably might experience an issue with unable to handle async with the following code below if you just copy directly

    await Item.insertMany(defaultItem).then(
      (result) => {
         console.log("Items added succesfully");
      }
    ).catch(
      (err) => {
         console.log(err);
      }
    )
    
    Login or Signup to reply.
  2. Item.insertMany(defultItems)
          .then(function () {
            console.log("Successfully saved defult items to DB");
          })
          .catch(function (err) {
            console.log(err);
          });
    
    Login or Signup to reply.
  3. The callback function that formally accompanied the insertMany() method has been deprecated (no longer in use).

    But you can use this instead;

    Item.insertMany(defultItems).then(function () {
        console.log("Successfully saved defult items to DB");
      }).catch(function (err) {
        console.log(err);
      });
    

    Note how the "then" and "catch" functions are continuous and a part of the "insertMany" method, as they are all joined using the dot (.) notation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search