ErrorMessage:
err: {
"type": "MongooseError",
"message": "Query was already executed: guilds.findOne({ name: 'Stream Squire' })",
Code:
async function lookUpDB(guildName, lookFor) {
const query = {name: guildName}
const guildModel = await model('guilds', GuildSchema)
const guildFind = guildModel.findOne(
query,
(err, doc) => {
console.log(doc || err)
}
)
return guildFind
}
Database Data:
Goal: I'm trying to make a function that will work anytime I need to find something in the database. Currently getting the error up top when i try to find the prefix. I'm not too familiar with mongoose or mongodb this is a discord bot to I was making to try and learn how to use it
Update: Guild Schema
const { model, Schema } = require('mongoose')
const GuildSchema = new Schema(
{},
{
strict: false,
versionKey: false,
}
)
module.exports = { GuildSchema, model }
Database:
const mongoose = require('mongoose')
const { logger } = require('../config/pino')
const { config } = require('../config/dotenv')
mongoose.connect(
//removed info
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
const { connection: db } = mongoose
db.on('connected', () => {
logger.info('Database connected')
})
db.on('disconnected', () => {
logger.info('Database disconnected')
})
db.on('error', (err) => {
logger.error(err)
})
module.exports = { db }
CodePudding user response:
Okay so, by convention, if you dont already have a Schema file declared create one,something like,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schemaDefinition = {
name: {
type: String,
required: true,
},
botName: {
type: String,
required: true,
},
Users:[{
type: String
}],
//add the rest
}
const GuildSchema = new Schema(schemaDefinition);
module.exports = mongoose.model('guilds', GuildSchema);
And then in your API logic file,export this schema model,
const GuildsModel = require('path to file');
async function lookUpDB(guildName, lookFor) {
const query = {name: guildName}
const guildFind = GuildsModel.findOne(
query,
(err, doc) => {
console.log(doc || err)
}
)
return guildFind
}