猫鼬保留重复元素
Mongoose keep duplicate elements
我有一个为 DiscordJS 创建公会条目的函数,但是当脚本启动时,如果多次调用该函数,它会创建大约 400 个重复文档,它通过 ID 创建并且 ID 是唯一的,所以它是不正常
我的模式结构只有一个 ID 类型字符串并且唯一为真
client.createGuild = async guild => {
const exist = await Guild.findOne({ id: guild.id });
if(!exist) {
await Guild.create({ id: guild.id }); // new Guild().save() keep duplicate too
}
}
好像if语句不存在
const Schema = mongoose.Schema;
const FooSchema = new Schema({
id: { type: String, index: true, unique: true }
});
const Foo = mongoose.model('Foo', FooSchema);
Foo.createIndexes();
如果集合已经存在。通过 atlas 或 cmd 手动为集合创建索引。
您可以将 getData 和 createData 函数合并为一个。这是示例:
const mongoose = require('mongoose');
async function getData(Guild, guild) {
if (!mongoose.connection.readyState) await mongoose.connect('MONGO_URL'); // In case you haven't connect to database
const data = await Guild.findOne({ id: guild.id }); // get data from database
if (!data) {
return new Guild({
id: guild.id,
}); // If no data exists for the guild, return new model
}
return data; // If the data already exists, return that
}
现在,如果您想从 mongodb 获取数据,只需调用该函数即可。如果没有,它会自动创建并保存一个新的。
如果您仍然有任何问题或您已经得到您需要的东西,请发表评论。
确保使用 await
调用该函数,否则它不会 return 数据。
我有一个为 DiscordJS 创建公会条目的函数,但是当脚本启动时,如果多次调用该函数,它会创建大约 400 个重复文档,它通过 ID 创建并且 ID 是唯一的,所以它是不正常
我的模式结构只有一个 ID 类型字符串并且唯一为真
client.createGuild = async guild => {
const exist = await Guild.findOne({ id: guild.id });
if(!exist) {
await Guild.create({ id: guild.id }); // new Guild().save() keep duplicate too
}
}
好像if语句不存在
const Schema = mongoose.Schema;
const FooSchema = new Schema({
id: { type: String, index: true, unique: true }
});
const Foo = mongoose.model('Foo', FooSchema);
Foo.createIndexes();
如果集合已经存在。通过 atlas 或 cmd 手动为集合创建索引。
您可以将 getData 和 createData 函数合并为一个。这是示例:
const mongoose = require('mongoose');
async function getData(Guild, guild) {
if (!mongoose.connection.readyState) await mongoose.connect('MONGO_URL'); // In case you haven't connect to database
const data = await Guild.findOne({ id: guild.id }); // get data from database
if (!data) {
return new Guild({
id: guild.id,
}); // If no data exists for the guild, return new model
}
return data; // If the data already exists, return that
}
现在,如果您想从 mongodb 获取数据,只需调用该函数即可。如果没有,它会自动创建并保存一个新的。
如果您仍然有任何问题或您已经得到您需要的东西,请发表评论。
确保使用 await
调用该函数,否则它不会 return 数据。