0

ErrorI used mongodb to create a database, when I use data1.save() then works, but when I used insertMany to save many it didn't work. It gives me this error: TypeError: Cannot read properties of undefined (reading 'length'), does anyone know what the problem might be? thanks!

Node.js v18.12.1, mongose 6.9.0


const mongoose = require("mongoose");


mongoose.set('strictQuery', true);
mongoose.connect("mongodb://localhost:27017/dataDB", {useNewUrlParser: true,});

const dataSchema = new mongoose.Schema ({
  name: String

});

const Data = mongoose.model("Data", dataSchema);


const data1 = new Data({
  name: "Welcome to you todoList"
});

const data2 = new Data({
  name: "Hit the + button to add a nem item"
});

const data3 = new Data({
  name: "<-- hit this to delate an item"
});

const dataItems = [data1, data2, data3];


Data.insertMany(dataItems, function(err){
   if (err){
       console.log(err);
  } else {
      consloe.log("Succesfully saved");
   }
});

Share experiences and problems with others, find solutions.

Dragan
  • 1
  • 2
  • .insertMany takes 3 args, does it still throw the error if you pass `[]` as the second arg? – Joe Feb 02 '23 at 18:33
  • In the future, please include the full error message, including indicating which part of the code it's saying is erroring. This makes it much easier for us to figure out the issue. – asportnoy Feb 03 '23 at 03:00
  • @Joe, I tried but it won't work again. – Dragan Feb 03 '23 at 10:59
  • @asportnoy, Ok, I will, thanks! I attached a picture of this error in the post. – Dragan Feb 03 '23 at 11:15
  • Please edit the question and add the error text. That picture is really hard to read on mobile, and we can't copy/paste filenames or error strings from the picture. – Joe Feb 03 '23 at 22:48

1 Answers1

0

The error message suggests that the dataItems array is undefined. To debug this issue, you can check if the array is indeed undefined by logging it to the console before using insertMany().

Another common cause of this error is if one of the elements in the array is not a valid instance of the model. Make sure that each element in the dataItems array is a valid instance of the Data model.

Try the following code:

console.log(dataItems);

Data.insertMany(dataItems, function(err){
  if (err){
    console.log(err);
  } else {
    console.log("Succesfully saved");
  }
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Thanks @ghazali, i try this and I managed to create a database and objects, but after that I get the same error again. I attached a picture of this error in the post. – Dragan Feb 03 '23 at 11:12