Mongoose批量操作未写入默认值。

4

我有以下模式:

//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个回答

4
您通过调用Command.collection.insert实际上绕过了Mongoose,这就是为什么您没有得到默认值的原因。相反,使用Model.insertMany以Mongoose的方式执行批量插入。
Command.insertMany(cmdList, function(err) {...});

刚刚看到另一篇帖子也提到了同样的事情,只不过建议使用Model.create()。我会采纳你的建议,谢谢。 - Trax
1
@Trax 这里最好使用 insertMany,因为它使用了批量写入(bulk writes),而 create 是逐个插入文档。 - JohnnyHK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接