我的 javascript 机器人遇到了一个问题,如果该服务器还没有自定义前缀,我的自定义前缀不会被保存,如果有,它会正确更新。
await mongo().then(async (mongoose) => {
try {
let newprefix = content.replace(`${prefix}setprefix `, '')
await prefixSchema.findOneAndUpdate({_id: guild.id}, {_id: guild.id, prefix: newprefix})
.then(async () => {
console.log(`updated prefix for guild: ${guild.id}`)
await channel.send(`Succesfully updated prefix for this server to '${newprefix}'`)
message.guild.me.setNickname(`[${newprefix}] - Helix`)
})
.catch(async (err) => {
console.error(`failed to update prefix for guild: ${guild.id}\n${err}`)
await channel.send(`Failed to update prefix.`)
})
console.log("saved to db")
} catch {
console.log("Something went wrong while saving new prefix for a server.")
} finally {
mongoose.connection.close()
}
机器人确实打印并发送它成功更新了前缀,但如果还没有 guild.id 的文档,则不会保存任何内容。我做错了什么,我该如何解决?
感谢阅读!
答案 0 :(得分:1)
Model.updateOne()
参数
[options.upsert=false]
«Boolean» 如果为真,并且没有找到文档,则插入一个新文档
无论 multi 选项的值如何,MongoDB 都只会更新与过滤器匹配的第一个文档。 如果您想覆盖整个文档而不是使用像 $set 这样的原子操作符,请使用 replaceOne()。 示例:
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
请访问 https://mongoosejs.com/docs/api.html#model_Model.updateOne 了解更多信息。