Tengo datos que ya se guardaron en mongoodb atlas, pero no sé cómo obtener y mostrar esos datos en mi respuesta de discordia de bot.
Así envío los datos
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") } });este es mi esquema
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);Y quiero mostrar los datos de esta manera, probé este código pero no funcionó.
client.on("message", msg => { if (msg.content === "!nickname"){ msg.reply("Your Nickname:", User.findById(nickname)) } });En MongoDB, tiene algunas formas de consultar datos de la base de datos. Algunos de ellos son: User.find() (para encontrar varios documentos),User.findById() (para obtener un documento por su id) y User.findOne (para encontrar solo el primer documento que coincida con los parámetros). Un ejemplo de cada uno de ellos sería:
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 }) Para encontrar los datos por el nickname , primero tendría que obtenerlos dividiendo el contenido del mensaje. Luego, tendría que consultar los datos utilizando uno de los métodos mencionados anteriormente y luego puede responder. Puedes hacer algo como esto:
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}`) })puede definir el esquema usando
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}`}) O puede traer el esquema y usar .then()
Schema.findOne({ userID: message.author.id }, async (err, data) => { // your code here });No olvide agregar la ruta de la carpeta de su esquema
const Schema = require('...') // your schema file de esta manera, busca los datos en la base de datos utilizando el ID de usuario porque userID findbyId() es el ID principal de la colección mongodb
El método findById() busca por campo _id. Así que puedes hacer esto:
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}`); }); } });O haz esto si quieres consultar con el apodo:
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); } ); } });