我有資料已經??保存在 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))
}
});
uj5u.com熱心網友回復:
在 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}`)
})
uj5u.com熱心網友回復:
您可以使用定義架構
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在資料庫中搜索資料
uj5u.com熱心網友回復:
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);
}
);
}
});
uj5u.com熱心網友回復:
您需要將實際的 Mongo ID 傳遞給 User.findById,如果您想通過 userID 或昵稱查找,請撰寫類似
User.find({ nickname })
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489435.html
標籤:javascript mongodb 猫鼬 不和谐.js mongodb-图集
