0

i have a js file createMoreUsers.js that imports the mongoose model from the user.js file which contains the userSchema. I wish to an array to hold objects of firstName and lastName but when i come to use mongoose insertMany() method it only saves the first object and not any others.

It outputs the following error instead. Error Occurred: E11000 duplicate key error collection: fcc-mail.users index: user_1 dup key: { user: null }

user.js file

const mongoose = require('mongoose')

let userSchema = new mongoose.Schema({

    firstName: String,
    lastName: String

});

const User = mongoose.model('User', userSchema);

module.exports = User;

createMoreUsers.js file


//requiring mongoose only to close the connection

const mongoose = require('mongoose');

//requiring the database file for connecting to the mongo db

const dbconnect = require('../database');

//create a new instance of the database connection 

new dbConnect.Database();

//lets require the mongoose model 

const UserModel = require('../models/user');

//creating an array of objects

let userArray = [

     {firstName: 'Charles', lastName: 'Parker'},
     {firstName: 'Thomas', lastName: 'Anderson'},
     {firstName: 'William', lastName: 'Wallace'},
     {firstName: 'Tin', lastName: 'Tin'}

]

UserModel.insertMany(userArray)
.then(function(docs){


    console.log('All user documents are saved to the database', docs);
    mongoose.connection.close();

})
.catch(function(err){

    console.error('Error Occurred: ', err.message);

});

Any advise. Always much appreciated.

Follow up - including my database.js file


const mongoose = require('mongoose');

const server = 'localhost:27017';
const databaseName = 'fcc-mail';


class Database {
    

    constructor() {
        this._connect()
    }

    _connect() {
         mongoose.connect(`mongodb://${server}/${databaseName}`, {useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true})
        .then(() => {
            console.log('Database connection success');
        })
        .catch((err) => {
            console.error('Database connection error', err);
        })
    }

}

module.exports.Database = Database;

If i need to use async/await in database.js file, how do i do so on a class ?

Sho.ayb
  • 3
  • 1
  • 4

2 Answers2

0

I've just tried the following code and it's working in my end. You can check this code snippet and get some idea.


// connect database
(async () => {
  try {
    await mongoose.connect(
      "your mongo database link here",
      { useUnifiedTopology: true, useNewUrlParser: true }
    );
    console.log("database connected...");

    // seed data
    const userArray = [
      { firstName: "Charles", lastName: "Parker" },
      { firstName: "Thomas", lastName: "Anderson" },
      { firstName: "William", lastName: "Wallace" },
      { firstName: "Tin", lastName: "Tin" }
    ];

    await User.deleteMany(); // removing all previous data (if any) (Never use this in production)
    const data = await User.insertMany(userArray);

    console.log(data);
  } catch (error) {
    console.log(error);
  }
})();
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23
  • I have tried this with an async function and await on the connection and on the insertMany() but i still get only the first doc being saved to the db. I get no error now on terminal but it used to say E11000 duplicate key error. My database connection is in difference file named database.js and i create a new instance of that connection using the new keyword. Since it saves one doc it means that it does indeed connect to the db but it does not bulk save the rest. thanks for your response. – Sho.ayb Mar 31 '21 at 23:48
0

Writing this answer for anyone else getting similar error E11000 duplicate key error.

According to this stackoverflow post: enter link description here

The issue is that there is already an index created with a null value, possibly because a collection was already created using the same Schema.

The solution is to drop the index. I dropped the index that was causing the issue from mongodb compass indexes tab and clicking on the trash bin to delete the index in question.

After doing so, i ran the file again and all my users were saved to the database.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sho.ayb
  • 3
  • 1
  • 4