今天,我決定制作一個 Discord RPG 機器人,這當然需要個人資料統計資訊,例如硬幣和實際用戶。因此,我搜索了有關如何使用 MongoDB 執行此操作的教程,但遇到了一個問題。當公會成員加入并且機器人正在運行時,資料不會完全沒有錯誤地保存,我不確定為什么會發生這種情況。我嘗試通過console.log(mongoose.connection.readyState)在機器人嘗試連接到資料庫后添加一行來對連接狀態進行故障排除。這將回傳1,這意味著連接正常。我找不到任何其他原因導致這種情況,所以我決定在思考幾個小時后提出一個問題。
(index.js):連接到資料庫
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => [
console.log("Connected to MongoDB Database successfully!"),
console.log(mongoose.connection.readyState)
]).catch((err) => {
console.error(err);
});
(profileSchema.js):創建組態檔架構
const mongoose = require("mongoose");
const profileSchema = new mongoose.Schema({
id: { type: String, require: true, unique: true },
serverid: { type: String, require: true },
coins: { type: Number, default: 0 },
bank: { type: Number }
});
const model = mongoose.model("ProfileModels", profileSchema);
module.exports = model;
(guildMemberAdd.js):創建資料并上傳到資料庫
const profileModel = require('../models/profileSchema');
module.exports = async(client, discord, member) => {
let profile = await profileModel.create({
id: member.id,
serverid: member.guild.id,
coins: 0,
bank: 0
})
profile.save();
}
uj5u.com熱心網友回復:
原因與您連接到 mongo 的方式有關
默認情況下,mongo 在連接到資料庫后關閉連接。要做到這一點,當連接到 mongo 時,傳入keepAlive選項,所以它看起來像:
mongoose.connect(process.env.MONGO_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true,
keepAlive: true
})
這將意味著與您的資料庫的活動連接將保持打開狀態
uj5u.com熱心網友回復:
您正在從 profileSchema.js 匯出“模型”并需要從 guildMemberAdd.js 匯出“profileModel”?所以從 profileSchema 匯入模型而不是 profileModel
uj5u.com熱心網友回復:
修復:通過添加 console.log 陳述句確保正在呼叫 guildMemberAdd 事件。如果不是,請檢查 guildMemberAdd 的代碼是否與其他事件代碼不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393906.html
標籤:javascript 节点.js MongoDB 猫鼬 不和谐.js
上一篇:使用點符號和$運算子更新貓鼬
