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

Time:08-09

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')

CodePudding user response:

You can use for looping function:

First, call your index:

const notificationschema = require('./schemas/notificationschema');
const notifs = await notificationschema.find({})
//This will make your data as array object.

Now After creating and calling your index. Use for loop:

for(let i = 0; i < notifs.length; i  ) {
  notificationschema.updateOne({
    User: notifs[i].memberID //I assume that this column is a member_id
  }, {
    $push: {
      Notifs: "Something you wanted to say here or whatsoever"
    }
  })
}

CodePudding user response:

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();
})
  • Related