简体   繁体   English

如何使用 mongoose 从 mongodb 读取特定数据?

[英]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.我有数据已经​​保存在 mongoodb atlas,但我不知道如何获取该数据并将其显示到我的机器人不和谐回复中。

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

In MongoDB, you have a few ways to query data from the database.在 MongoDB 中,您有几种方法可以从数据库中查询数据。 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).其中一些是: User.find() (查找多个文档)、User.findById() (通过其 id 获取文档)和User.findOne (仅查找与参数匹配的第一个文档)。 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.要通过nickname查找数据,首先必须通过拆分消息内容来获取它。 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}`)
})

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()或者您可以带上架构并使用.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这样它使用userID在数据库中搜索数据,因为findbyId()是主要的 mongodb 集合 id

findById() method finds by _id field. findById()方法通过 _id 字段查找。 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);
        }
        );
    }
});

您需要将实际的 Mongo ID 传递给 User.findById,如果您想通过 userID 或昵称查找,请编写类似

User.find({ nickname })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM