如何将字符串推送至MongoDB集合所有用户文档的Notifs数组?
问题描述
我用Discord.js编写了一个announcement子命令用于发布公告,现在需要将输入的公告内容推送到所有用户对应的notificationschema的Notifs数组中,相关代码如下:
子命令代码
.addSubcommand(subcommand => subcommand .setName('announcement') .setDescription('向所有用户发送公告。') .addStringOption(option => option .setName('announcement1') .setDescription('公告内容') .setRequired(true))),
当前命令处理代码
if (interaction.options.getSubcommand() === 'announcement') { const ann = interaction.options.getString('announcement1') const notificationschema = require('./schemas/notificationschema') }
Schema定义
const mongoose = require('mongoose') const notificationschema = mongoose.Schema({ User: String, Notifs: Array, Read: Boolean, }) module.exports = mongoose.model('notification', notificationschema, 'notification')
请问该如何实现将公告内容推送至所有用户的Notifs数组中?
解决方案
可以利用Mongoose的updateMany()方法批量更新所有用户文档,通过$push操作符将公告内容追加到Notifs数组末尾。注意数据库操作是异步的,处理函数需要标记为async并使用await等待操作完成。
修改后的命令处理代码如下:
// 确保你的命令处理函数是异步的,比如: // module.exports = { // data: ..., // async execute(interaction) { // // 处理逻辑写在这里 // } // } if (interaction.options.getSubcommand() === 'announcement') { const ann = interaction.options.getString('announcement1') const notificationschema = require('./schemas/notificationschema') try { // 批量更新所有文档,将公告内容推送到Notifs数组 const result = await notificationschema.updateMany( {}, // 空查询条件匹配所有文档 { $push: { Notifs: ann } } // 使用$push追加元素到数组 ) // 给用户反馈操作结果 await interaction.reply(`已成功向${result.modifiedCount}个用户推送公告!`) } catch (error) { console.error('推送公告出错:', error) await interaction.reply('推送公告失败,请稍后重试。') } }
关键说明
updateMany({}, { $push: { Notifs: ann } }):第一个参数为空对象,代表匹配集合中所有文档;第二个参数通过$push操作符,将公告内容追加到每个文档的Notifs数组中。- 用
try/catch捕获数据库操作可能出现的错误,避免程序崩溃同时给用户明确反馈。 - 必须保证命令处理函数是异步的(带有
async关键字),否则await语法会报错。
内容的提问来源于stack exchange,提问作者Pickle
相关产品推荐
相关产品推荐

