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 ?