[英]How to save data without creating new object on database mongoose?
我尝试使用 bot 命令保存数据,但每次我提交数据时它都会创建新对象,我只想让它成为 1 个对象,但每次同一个用户提交数据时,它都会自动获得更改/更新,而不是创建新对象。
这就是我保存数据的方式
const subregis = "!reg ign:";
client.on("message", msg => {
if (msg.content.includes(subregis)){
const user = new User({
_id: mongoose.Types.ObjectId(),
userID: msg.author.id,
nickname: msg.content.substring(msg.content.indexOf(":") + 1) // so basically anything after the : will be the username
});
user.save().then(result => console.log(result)).catch(err => console.log(err));
msg.reply("Data has been submitted successfully")
}
});
这是我的架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
userID: String,
nickname: String,
});
module.exports = mongoose.model("User", profileSchema);
每次我执行命令!reg ign
时,它都会添加新对象,而不是保存/更新现有的用户 ID。
如果要更新现有User
,应使用findOneAndUpdate
函数:
const subregis = '!reg ign:';
client.on('message', async (msg) => {
try {
if (msg.content.includes(subregis)) {
const updatedUser = await User.findOneAndUpdate(
{ userID: msg.author.id },
{
nickname: msg.content.substring(msg.content.indexOf(':') + 1), // so basically anything after the : will be the username
},
{
new: true, // Return an updated instance of the User
}
);
console.log(updatedUser);
msg.reply('Data has been submitted successfully');
}
} catch (err) {
console.log(err);
}
});
您唯一需要做的就是在创建集合之前检查是否有与该用户相关的数据。
Schema.findOne({ userID: msg.author.id }, async (err, data) =>{
if (data) {
return msg.reply({content: `you already have a nickname, it's ${data.nicknamd}})
}
if (!data) {
// Create the Schema
}
})
如果要更新昵称,请使用
const newdata = Schema.findOneandUpdate({}) ...
//then follow what lpizzini said above
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.