[英]How do I make the profiles for my MongoDB Collection add a new field if the field it's looking for is missing in Discord.JS?
the very bottom field listed ("dabmeup") is being created correctly along with the other fields if a user that doesn't have a profile, but when a user already has the profile it won't update.如果用户没有个人资料,则列出的最底部字段(“dabmeup”)与其他字段一起正确创建,但是当用户已经拥有个人资料时,它不会更新。 How would I correctly make the code add the field without overwriting what that user already has?
我如何正确地让代码添加字段而不覆盖用户已经拥有的内容? Below is a section my "message.js" file where it checks actually adds the fields.
下面是我的“message.js”文件的一部分,它检查实际添加了字段。
let profileData;
try {
profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 1000,
bank: 0,
sent: { type: Number },
received: { type: Number },
owner: { type: Number, default: 0 }, //code: 1
admin: { type: Number, default: 0 }, //code: 1
nyaw: { type: Number, default: 0 }, //code: 2
donator: { type: Number, default: 0 }, //code: 3
dev: { type: Number, default: 0 }, //code: 4
tester: { type: Number, default: 0 }, //code: 4
oneK: { type: Number, default: 0 }, //code: 6
tenK: { type: Number, default: 0 }, //code: 7
hundK: { type: Number, default: 0 }, //code: 8
oneM: { type: Number, default: 0 }, //code: 9
tenM: { type: Number, default: 0 }, //code: 10
hundM: { type: Number, default: 0 }, //code: 11
dabmeup: {type: Number, default: 0} //code: 12
});
profile.save();
}
} catch (err) {
console.log(err);
}
In your models if it already defined default 0 so you don't need to add it in create()
and save()
is using commit when modify an existing documents.在您的模型中,如果它已经定义了默认值 0,那么您不需要在
create()
添加它,并且save()
在修改现有文档时使用 commit。
In summary your code should look like总之你的代码应该看起来像
let profileData;
try {
profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 1000,
bank: 0,
sent: 0,
received: 0,
});
}
} catch (err) {
console.log(err);
}
You can run a simple script that will iterate through all documents without the dabmeup
property, and update them all to include it.您可以运行一个简单的脚本,该脚本将遍历所有没有
dabmeup
属性的文档,并更新它们以包含它。 This only has to be run once.这只需要运行一次。
profileModel.updateMany(
{ dabmeup: { $exists: false } }, // the $exists operator checks if a field exists
{ $set: { dabmeup: 1 } } // the $set operator will set a field without modifying the rest of the document
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.