MongooseError: Model.findOne() no longer accepts a callback at Function
Asked Answered
L

4

13

I've encountered a problem while setting up mongoose.

Here is my code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const testSchema = require(`../../Schemas.js/test`);

module.exports = {
    data: new SlashCommandBuilder()
    .setName('dbtest')
    .setDescription('db test'),
    async execute(interaction) {

        testSchema.findOne({ GuildID: interaction.guild.id, UserID: interaction.user.id}, async(err, data) => {
            if (err) throw err;

            if (!data) {
                testSchema.create({
                    GuildID: interaction.guild.id,
                    UserID: interaction.user.id
                })
            }

            if (data) {
                console.log(data)
            }
        })
    }
}

My error:

/Users/akimfly/akim-slash-bot/node_modules/mongoose/lib/model.js:2131
    throw new MongooseError('Model.findOne() no longer accepts a callback');
          ^

MongooseError: Model.findOne() no longer accepts a callback
    at Function.findOne (/Users/akimfly/akim-slash-bot/node_modules/mongoose/lib/model.js:2131:11)
    at Object.execute (/Users/akimfly/akim-slash-bot/src/commands/Community/databasetest.js:10:20)
    at Object.execute (/Users/akimfly/akim-slash-bot/src/events/interactionCreate.js:12:21)
    at Client.<anonymous> (/Users/akimfly/akim-slash-bot/src/functions/handleEvents.js:8:58)
    at Client.emit (node:events:513:28)
    at InteractionCreateAction.handle (/Users/akimfly/akim-slash-bot/node_modules/discord.js/src/client/actions/InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (/Users/akimfly/akim-slash-bot/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (/Users/akimfly/akim-slash-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:352:31)
    at WebSocketShard.onPacket (/Users/akimfly/akim-slash-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:489:22)
    at WebSocketShard.onMessage (/Users/akimfly/akim-slash-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:328:10)
Langue answered 6/3, 2023 at 9:52 Comment(1)
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Landfall
A
16

Mongo dropped support for callbacks from its node.js driver as of version 5.0 in favour of a Promise-only public API. Mongoose also dropped callback support in v7 so findOne() and other methods now always return a promise.

The full list of methods affected can be found here.

You can use async/await instead:

module.exports = {
  data: new SlashCommandBuilder().setName('dbtest').setDescription('db test'),
  async execute(interaction) {
    try {
      const data = await testSchema.findOne({
        GuildID: interaction.guild.id,
        UserID: interaction.user.id,
      });

      if (!data) {
        testSchema.create({
          GuildID: interaction.guild.id,
          UserID: interaction.user.id,
        });
      }

      if (data) {
        console.log(data);
      }
    } catch (error) {
      console.log(error);
    }
  },
};

Or just good old thens:

module.exports = {
  data: new SlashCommandBuilder().setName('dbtest').setDescription('db test'),
  execute(interaction) {
    testSchema
      .findOne({
        GuildID: interaction.guild.id,
        UserID: interaction.user.id,
      })
      .then((data) => {
        if (!data) {
          testSchema.create({
            GuildID: interaction.guild.id,
            UserID: interaction.user.id,
          });
        }

        if (data) {
          console.log(data);
        }
      })
      .catch((err) => console.log(err));
  },
};
Araby answered 6/3, 2023 at 10:10 Comment(0)
D
7

MongooseError: Model.find() no longer accepts a callback

*you can use async/await or promises(then)

Model.find().then((data) => {
 console.log(data);
....
})
Drat answered 25/3, 2023 at 12:47 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Landfall
Please read "How to Answer" and "Explaining entirely code-based answers". It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.Necaise
H
0

Along with the above mentioned findOne() these are all the other functions Mongoose docs that generate the same error since the usage of callback functions has been deprecated in Mongoose version 7.x. Hence you can use async/await or promises. For more go through this thread Mongoose Discussion forum

Ex:1

Collection.find().then(function(documents){
   console.log(documents);
})

Ex:2

 Collection.insertMany([doc1,doc2]).then(function () {
     console.log("Successfully inserted Multiple docs into collection);
   }).catch(function (err) {
     console.log(err);
   });
Haber answered 10/4, 2023 at 13:34 Comment(1)
Provide context for links: Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the external resource is unreachable or goes permanently offline.Necaise
O
0

i was use mongoose "mongoose": "^8.0.4" in my package.json, and i don't change all query in all routes of my backend, so i have change to version mongoose to "mongoose": "^6.7.2", its work for me.

Ostend answered 13/1 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.