Home > Software engineering >  How to read the specific data from mongodb using mongoose?
How to read the specific data from mongodb using mongoose?

Time:06-11

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))
  }
});

CodePudding user response:

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

CodePudding user response:

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);
        }
        );
    }
});

CodePudding user response:

You need to pass the actual Mongo ID into User.findById, if you want to find by userID or nickname write something like

User.find({ nickname })

CodePudding user response:

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({ nickname: nickname })
    if (!data) return
    message.channel.send(`The nickname is ${nickname}`)
})
  • Related