Nodejs Discord Bot 服务器在从 MongoDB "Duplicate Key Error"后崩溃



我是MongoDB的新手,我有一个用Nodejs制作的不和谐机器人,它存储来自不和谐服务器成员的电影推荐提交,服务器存储发送到MongoDB数据库的数据(使用Mongoose)。我试图防止在数据库中重复记录,设置猫鼬模式属性"唯一";到真正的帮助,但每当有人提交一个电影标题,已经在数据库中,服务器只是抛出一个重复的键错误和崩溃,我如何防止重复的条目,同时防止服务器崩溃时发生,而不是可能只是发送一个回复给用户,电影已经存在于数据库中?

我的电影提交处理程序:

if(command.includes('sendreclink!')){
const arr = message.content.split('!')
console.log(arr[1], arr[2])
const movieTitle = arr[1].trim().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
const movie = new Movie({title: movieTitle , link: arr[2]})
await movie.save()
message.reply(`${movieTitle} has been added to the list`)

}

我的猫鼬:

mongoose.connect(process.env.MONGO_KEY)
const movieSchema = new mongoose.Schema({
title: {type: String, unique: true, require: true},
link: {type: String, unique: true, sparse: true}
});
module.exports = mongoose.model('Movie', movieSchema);

发送重复条目时在节点控制台中出现错误消息:

MongoServerError: E11000 duplicate key error collection: test.movies index: title_1 dup key: { title: "American Movie" }

我尝试将Schema唯一属性设置为true并删除数据库并从头开始。

您可以将一些代码放入一个try-catch块,像这样

try {
await movie.save();
} catch(ex) {
console.log(ex)
}

这样,即使有错误,你的服务器也不会崩溃

最新更新