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))
}
});
4
Answers
findById()
method finds by _id field. So you can either do this:Or do this if you want to query with nickname:
You need to pass the actual Mongo ID into User.findById, if you want to find by userID or nickname write something like
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), andUser.findOne
(to find only the first document which matches the parameters). An example of each of them would be: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:you can define the Schema by using
Or you can bring the schema and use
.then()
Don’t forget to add your schema folder path
this way it search for the data in database using the
userID
becausefindbyId()
is the main mongodb collection id