I’ve looked everywhere and I cannot figure out why I get this error while I try to create and save multiple documents with Mongoose.
It is working to save individual documents, but when I run the script to add multiple documents with .insertMany() I get the following message in terminal and I have no clue what to do with it.
/Users/FruitsProjectMongoose/node_modules/mongoose/lib/model.js:3519
for (let i = 0; i < error.writeErrors.length; ++i) {
^
TypeError: Cannot read properties of undefined (reading 'length')
at /Users/FruitsProjectMongoose/node_modules/mongoose/lib/model.js:3519:47
at collectionOperationCallback (/Users/FruitsProjectMongoose/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:194:24)
at /Users/FruitsProjectMongoose/node_modules/mongodb/lib/utils.js:349:66
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
It would be an understatement to say that I have tried everything that I could think of/find across the web. I’ve messaged a few devs. and they’ve recommended me to try some things but no luck. I really need some help with this. I start to think it might be something wrong with my system.
I’ve installed MongoDB through HomeBrew and Mongoose through npm in the past two days so everything is up-to-date.
Here is my simple JS script:
const mongoose = require("mongoose");
mongoose.set('strictQuery', false);
// Connect to MongoDB by port and catch errors.
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB')
.then(() => console.log('Connected!'));
// Defining a Model Schema.
const Schema = mongoose.Schema;
const fruitSchema = new Schema({
name: {
type: String,
require: true
},
rating: {
type: Number,
require: true
},
review: {
type: String,
require: true
}
});
const peopleSchema = new Schema({
name: String,
age: Number
});
// Create a Model.
const Fruit = new mongoose.model("Fruit", fruitSchema);
const People = new mongoose.model("People", peopleSchema);
// Create & Save a Document.
const fruit = new Fruit({
name: "Banana",
rating: 10,
review: "Perfection!"
});
// await fruit.save();
const people = new People({
name: "Eduard",
age: 25
});
// await people.save();
// Create & Save docs. in Bulk.
const kiwi = new Fruit({
name: "Kiwi",
rating: 9,
review: "Great, kinda expensive!"
});
const orange = new Fruit({
name: "Orange",
rating: 6,
review: "Too sweet."
});
const apple = new Fruit({
name: "Apple",
rating: 7,
review: "Great fruit!"
});
Fruit.insertMany([kiwi, orange, apple], function(err) {
if (err) {
console.log(err);
} else {
console.log("Succesfully saved to fruitsDB");
}
});
mongoose.connection.close();
};
MongoDB server is running on brew services start mongodb-community
.