我嘗試使用 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。
uj5u.com熱心網友回復:
您唯一需要做的就是在創建集合之前檢查是否有與該用戶相關的資料。
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
uj5u.com熱心網友回復:
如果您想更新現有的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);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489433.html
標籤:javascript mongodb 猫鼬 不和谐.js
