Foreach document mongoose

Viewed 202

I am trying to loop through all the documents in a collection in mongodb.

Here is what I have.

module.exports = {
    name: `store`,
    aliases:['shop'],

    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
run: async(client, message, args) => {
    
    const exampleEmbed = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Boblox Shop')
    .setDescription('Buy stuff with $buy <id>')
    const items = require('./shop')

    items.find({}).then(function(documents) {
      
        documents.forEach(function(u) {
            exampleEmbed.addField(`${u.ItemName}`, `Price: ${u.Price}`)

        });
    })

    .setTimestamp()
}
}

Shop is a schema. Here is the code for shop

const mongoose = require("mongoose")

const commandsRan = mongoose.Schema({
    ItemName:String,
    Price:Number,
    Stock:Number,
    Rarity:String,
    Description:String,
    Emoji:String

})

module.exports = mongoose.model("Shop", commandsRan, 'shopitems')

When I run the code shop command, I get this error: TypeError: items.find(...).then(...).setFooter is not a function

How do I loop through every document in the collection and add a field to the embed?

1 Answers

So first of all, I've realised that your code snippet isn't the exact code you are running, as the thrown error mentions the error of ...setFooter and the function, setFooter isn't even mentioned in the code snippet. There is also a stray setTimestamp function, at the end of the items.find(), you can move that to the end of the embed.

module.exports = {
  name: `store`,
  aliases:['shop'],

  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async(client, message, args) => {

    const exampleEmbed = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Boblox Shop')
    .setDescription('Buy stuff with $buy <id>')
    .setTimestamp();

    const items = require('./shop');

    items.find({}).then(function(documents) {
      documents.forEach(function(u) {
        exampleEmbed.addField(`${u.ItemName}`, `Price: ${u.Price}`);
      });
    })
  }
}

I've generally just reformatted the code, and shifted the setTimestamp function to the end of of the MessageEmbed constructor, the items.find shouldn't have any problems.

Related