![](/img/trans.png)
[英]Update an embedded array inside an document if it exists otherwise create a new document MongoDB NodeJS
[英]Update mongodb document, if the document exists, else create
因此,我正在嘗試為我和我的朋友制作一個 Discord 機器人,用於跟蹤 CS GO 10 mans 中的統計數據,並且我正在使用 Cheerio 從為我們提供統計數據的站點進行網絡抓取,然后將它們傳遞到 mongodb。 報廢功能工作正常,但我試圖弄清楚如何避免為每個用戶創建重復的文檔。 如果我輸入 *userid 857575 它會提取該用戶的統計信息並將其放入數據庫中,但是如果我多次調用它,它會在數據庫中生成多個文檔。 我的問題是,如果不和諧中的消息作者與數據庫中的用戶名匹配,我將如何讓 mongodb 更新文檔? 因此,如果用戶名 bob 發送 *userid3939 並且 bob 已存在於數據庫中,請更新文檔。 如果 bob 不存在,則創建文檔。 下面的代碼,感謝任何提示。
module.exports.run = async (bot, message, args) => {
console.log(args);
var userUrl = 'https://popflash.site/user/' +args;
console.log(userUrl);
console.log(message.member.user.tag);
rp(userUrl)
.then(function (html) {
const arr = [];
var i = 0;
$('.stat-container', html).each(function (key, value) {
arr[i++] = $(this).find(".stat").text();
});
const stats = new Stats({
_id: mongoose.Types.ObjectId(),
userName: message.member.user.tag,
userId: args,
HLTV: arr[0],
ADR: arr[1],
HS: arr[2],
W: arr[3],
L: arr[4],
T: arr[5],
win_percent: arr[6]
});
stats.save()
.then(function (result) {
let botembed = new Discord.RichEmbed()
.setDescription(message.member.user + "'s 10 Man stats")
.setColor("#15f153")
.addField("stats", result)
return message.channel.send(botembed);
})
})
}
module.exports.help = {
name: "userid"
}
通過db.collection.update
,您可以指定upsert: true
選項以獲得我認為您想要的行為。 如果匹配,它將更新現有記錄,否則將創建新記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.