繁体   English   中英

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

[英]How to read the specific data from mongodb using mongoose?

我有数据已经​​保存在 mongoodb atlas,但我不知道如何获取该数据并将其显示到我的机器人不和谐回复中。

这就是我提交数据的方式

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

这是我的架构

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

我想显示这样的数据,我尝试了这段代码但没有用。

client.on("message", msg => {
  if (msg.content === "!nickname"){ 
      msg.reply("Your Nickname:", User.findById(nickname))
  }
});

在 MongoDB 中,您有几种方法可以从数据库中查询数据。 其中一些是: User.find() (查找多个文档)、User.findById() (通过其 id 获取文档)和User.findOne (仅查找与参数匹配的第一个文档)。 他们每个人的一个例子是:

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

要通过nickname查找数据,首先必须通过拆分消息内容来获取它。 然后您必须使用上述方法之一查询数据,然后您才能回复。 你可以这样做:

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

您可以使用定义架构

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

或者您可以带上架构并使用.then()

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

不要忘记添加您的架构文件夹路径

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

这样它使用userID在数据库中搜索数据,因为findbyId()是主要的 mongodb 集合 id

findById()方法通过 _id 字段查找。 所以你可以这样做:

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

或者,如果您想使用昵称进行查询,请执行此操作:

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