Mongoose Bulk没有写默认值

时间:2016-12-17 14:31:57

标签: node.js mongodb mongoose

我有以下架构:

//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);

如果我添加这样的新命令:

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

一切正常并且写入默认值但是如果我尝试插入多个命令,则默认值不会添加到数据库中,这里是我使用的代码:

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);
    }
});

1 个答案:

答案 0 :(得分:2)

您通过调用Command.collection.insert有效地绕过了Mongoose,这就是为什么您没有获得默认值。

相反,使用Model.insertMany执行批量插入Mongoose方式:

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