Search code examples
javascriptnode.jsmongodbmongoosediscord.js

How do you push a string into all users documents in a mongodb collection?


This is my subcommand code:

.addSubcommand(subcommand =>
  subcommand
  .setName('announcement')
  .setDescription('Announce something to every user. ')
  .addStringOption(option =>
    option
    .setName('announcement1')
    .setDescription('Announcement content')
    .setRequired(true))),

This is my code so far for the command:

if (interaction.options.getSubcommand() === 'announcement') {
    const ann = interaction.options.getString('announcement1')
    const notificationschema = require('./schemas/notificationschema')

}

I am trying to push the contents of the variable ann into everyone's notificationschema into the notifs array.

How would I do this?

This is my schema:

const mongoose = require('mongoose')

const notificationschema = mongoose.Schema({

        User:String,
        Notifs:Array,
        Read:Boolean,

        
})
module.exports = mongoose.model('notification', notificationschema, 'notification')

Solution

  • You can use the find function from mongoose, then loop through all the found results.

    const foundSchemas = await notificationSchema.find({});
    
    foundSchemas.forEach(result => {
    result.Notifs.push('Your Notification');
    result.save();
    })