如何在mongodb中增加值



我想增加数据库中的当前数目。

示例:如果数据库中的数字为0,我希望每次使用PostImage命令时它都增加1。

错误:当我console.log(debug)它给出undefined

const attachment = await interaction.options.getAttachment("input");
const caption = await interaction.options.getString("caption");
const channel = client.channels.cache.get("988214204660064286");
const embed = new MessageEmbed()
.setAuthor({ name: `${username} Posted`, iconURL: `${profilePicData}` })
.setColor("#303236")
.setDescription(`${caption}`)
.setImage(`${attachment.url}`)
.setFooter({ text: `user ID: ${userId}`, iconURL: `${profilePicData}` })
channel.send({ embeds: [embed] }).then(async (msg) => {
await msg.react("👎");
await msg.react("👍");
});
db.findOneAndUpdate({
UserId: userId,
PostAmount: 1
})
const dubug = data.map((x) => `${x.PostAmount}`).join('n');
console.log(dubug)

增加mongoose上的数据使用{$inc: {your_data}}

db.findOneAndUpdate({
UserId: userId,
PostAmount: 1 //You can now remove these one.
}, {$inc: {PostAmount: +1}}, async(err, data) => {
if(data) {
data.PostAmount += 1;
await data.save();
}
})

你应该删除这些代码行PostAmount: 1因为UserId会在数据库中找到自己的数据。

要将PostAmount的值增加1,可以简单地获取文档,将PostAmount的值更改为PostAmount + 1并保存文档

let doc = await db.findOne({ UserId: userId });
doc.PostAmount = doc.PostAmount + 1;
await doc.save();

除此之外,debug返回undefined,因为它没有定义。这可能是因为在调试定义中,它试图映射data,我也没有看到定义。

最新更新