[英]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.