Node.js MongoError: E11000 重复键错误集合:

时间:2021-07-09 09:21:54

标签: node.js mongodb mongoose discord.js

我正在使用 djs bot,但遇到了一个我不知道如何解决的错误 我看过https://docs.mongodb.com/manual/indexes/NodeJs, Mocha and Mongoose 但这里的信息似乎没有任何帮助 -

错误发生在这里 -

const Data = await serverModel.findOne({ serverID: message.guild.id });
    try{
        console.log(`checking if a database exists for ${message.guild}`);
        console.log(Data);
        if(!Data) {
            console.log(`Data base doent exist for ${message.guild}`);
            console.log(`Creating a database for ${message.guild}`);
            const server = await serverModel.create({
                serverID: message.guild.id,
                calling: 'no',
                channel: null,
                talkingWith: null,
                stickyChannel: null,
                stickyMessage: null,
                stickyID: null,
            });
            console.log('shit');
            server.save();
            return;
        }

    }
    catch(err) {
        console.log(err);
    }

这是我的 serverModel/serverSchema -

const mongoose = require('mongoose');

// ServerSchema
const ServerSchema = new mongoose.Schema({
    serverID: { type: String, require: true, unique: true, sparse:true },
    calling: { type: String, require: true, unique: false, sparse:true },
    channel: { type: String, require: true, unique: false, sparse:true },
    talkingWith: { type: String, require: true, unique: false, sparse:true },
    stickyChannel: { type: String, require: true, unique: false, sparse:true },
    stickyMessage: { type: String, require: true, unique: false, sparse:true },
    stickyID: { type: String, require: true, unique: false, sparse:true },
});

const model = mongoose.model('ServerSchema', ServerSchema);

module.exports = model;

最后这是我得到的错误 -

checking if a database exists for Vixo
null
Data base doent exist for Vixo
Creating a database for Vixo  
MongoError: E11000 duplicate key error collection: database.serverschemas index: stickyChannel_1 dup key: { stickyChannel: null }

1 个答案:

答案 0 :(得分:1)

似乎已经有记录的“stickyChannel”参数为空值。那么您可以尝试通过简单地为每个参数分配值来创建新记录吗?

尝试使用以下代码创建新记录:

`const server = await serverModel.create(
 { serverID: message.guild.id, 
   calling: 'no', 
   channel: 'test', 
   talkingWith: 'test', 
   stickyChannel: 'test, 
   stickyMessage: 'test, 
   stickyID: 'test', 
});`