Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
How to read the specific data from mongodb using mongoose?

I have data that already saved at mongoodb atlas, but i dont know how to get and display that data to my bot discord reply.

This is how i submit the data

const subregis = "!reg ign:";
client.on("message", msg => {
  if (msg.content.includes(subregis)){ 
      const user = new User({
        _id: mongoose.Types.ObjectId(),
        userID: msg.author.id,
        nickname: msg.content.substring(msg.content.indexOf(":") + 1)
      });
      user.save().then(result => console.log(result)).catch(err => console.log(err));
      msg.reply("Data has been submitted successfully") 
  }
});

This is my schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userID: String,
    nickname: String,
});

module.exports = mongoose.model("User", profileSchema);

And i want to show the data like this, i try this code but didnt work.

client.on("message", msg => {
  if (msg.content === "!nickname"){ 
      msg.reply("Your Nickname:", User.findById(nickname))
  }
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In MongoDB, you have a few ways to query data from the database. Some of them are: User.find() (to find multiple documents), User.findById() (to get a document by its id), and User.findOne (to find only the first document which matches the parameters). An example of each of them would be:

User.find({ query }, function (err, data) {
    if (err) throw err
    console.log(data) // This will return all of the documents which match the query
})
User.findById({ id }, function (err, data) {
    if (err) throw err
    console.log(data) // This will return the document with the matching id given
})
User.findOne({ query }, function (err, data) {
    if (err) throw err
    console.log(data) // This will return the first document which matches the query
})

To find the data by the nickname, you would first have to get it by splitting the message content. Then you would have to query the data by using one of the methods mentioned above and then you can respond back. You can do something like this:

client.on('message', async (message) => {
    const args = message.slice(1).split(' ')
    const command = args.shift().toLowerCase()
    const nickname = args.join(' ')
    const data = await User.findOne({ userId: message.author.id })
    if (!data) return
    message.channel.send(`The nickname is ${nickname}`)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

you can define the Schema by using

const data = Schema.findOne({ UserID: message.author.id })
 const nick = data.nickname;
if (!data) return message.reply({content: 'You have no data'})
message.reply({content: `Your nickname is ${nick}`})

Or you can bring the schema and use .then()

Schema.findOne({ userID: message.author.id }, async (err, data) => {
   // your code here
   });

Don't forget to add your schema folder path

const Schema = require('...') // your schema file

this way it search for the data in database using the userID because findbyId() is the main mongodb collection id

about 4 years ago · Juan Pablo Isaza Relatório

0

findById() method finds by _id field. So you can either do this:

client.on("message", msg => {
    if (msg.content === "!nickname"){
        // reply by User find by _id mongoose
        User.findById(id, (err, user) => {
            if (err) return console.error(err);
            msg.reply(`Your nickname is ${user.nickname}`);
        });
    }
});

Or do this if you want to query with nickname:

client.on("message", msg => {
    if (msg.content === "!nickname"){
        // reply by User find by nickname mongoose
        User.findOne({nickname: "nickname"}, (err, user) => {
            if (err) return console.log(err);
            msg.reply("Your Nickname:", user.nickname);
        }
        );
    }
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda