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.
The error message suggests that the
dataItemsarray is undefined. To debug this issue, you can check if the array is indeed undefined by logging it to the console before usinginsertMany().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
dataItemsarray is a valid instance of the Data model.Try the following code: