Trax
Trax

Reputation: 1558

Mongoose Bulk not writing defaults

I have the follwoing schema:

//commands.js
const mongoose = require('bluebird').promisifyAll(require('mongoose'));

// define the schema for our account data
const commandsSchema = mongoose.Schema({
  cmdName : { type: String, required: true, unique: true},
  description: {type: String},
  help: {type: String},
  accessRequired: {type: Number,default: 0},
  enabled: {type: Boolean, default: true }
},{timestamps : true});

module.exports = mongoose.model('Commands', commandsSchema);

If I add a new command like this:

let addCommand = new Command();
addCommand.cmdName= 'whois';
addCommand.description = 'Retrieve character information from server.';
addCommand.help = '!whois <character name>';
addCommand.save();

Everything works properly and the default values are written however if I try to insert multiple command the default values are not added to the database, here's the code I use:

let cmdList = [];

cmdList.push({
    cmdName: 'whois',
    description: 'Retrieve character information from server.',
    help: '!whois <character name>',
});

cmdList.push({
    cmdName: 'shutdown',
    description: 'Shutdown bot.',
    help: '!shutdown'
});
Command.collection.insert(cmdList, {
    w: 0,
    keepGoing: true
}, function(err) {
    if (err) {
        console.log(err);
    }
});

Upvotes: 4

Views: 1248

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312075

You're effectively bypassing Mongoose by calling Command.collection.insert, so that's why you're not getting the defaults.

Instead, use Model.insertMany to perform the bulk insert the Mongoose way:

Command.insertMany(cmdList, function(err) {...});

Upvotes: 4

Related Questions