Home > Enterprise >  Mongoose cannot .insertMany()
Mongoose cannot .insertMany()

Time:01-27

I've looked everywhere and I cannot figure out why I get this error while I try to create and save documents with Mongoose.

It has worked to save individual documents with await fruit.save();, 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.

The fruitsDB exists and I am able to access and view the collections and the individually added documents through the MongoDB shell mongosh.

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.

CodePudding user response:

This error is likely caused by an issue with the Mongoose library. To fix it, try updating the Mongoose library to the latest version. You can do this by running the following command in your terminal:

npm install mongoose@latest --save

If the "error" object is not defined, make sure that it is properly initialized before attempting to access its properties.

CodePudding user response:

I've missed a set of curly braces. So the correct syntax is this.

    await Fruit.insertMany([kiwi, orange, apple], {function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log("Succesfully saved to fruitsDB");
        }
    }});
  • Related