'How to solve this error: "MongoNotConnectedError: MongoClient must be connected to perform this operation"?
I am starting with mongoose and mongo atlas. I have been able to establish the connection and I am performing the crud. The issue is that except for the get requests, all the others throw me an error when making them: "MongoNotConnectedError: MongoClient must be connected to perform this operation". But despite this, it ends up performing the operation the first time. Attached the error and the code. Looking for help.
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const Contact = require('./models/contact');
const app = express();
app.use(cors());
app.use(express.json());
const PORT = process.env.PORT || 3001;
const db = mongoose.connection;
app.get('/api/persons', (request, response) => {
Contact.find({})
.then(contacts => {
response.json(contacts);
db.close();
})
.catch(error => console.log(error.message));
});
app.post('/api/persons', (request, response) => {
const { content } = request.body;
if(!content.name || !content.number) {
return response.status(400).json({
error: 'content missing',
})
};
const newContact = new Contact({
name: content.name,
number: content.number,
});
newContact.save((error, contact) => {
if(error) console.log(error.message);
response.json(contact);
db.close();
});
});
app.get('/api/persons/:id', (request, response, next) => {
Contact.findById(request.params.id)
.then(contact => {
contact ? response.json(contact) : response.status(404).end();
})
.catch(error => next(error));
});
app.put('/api/persons/:id', (request, response, next) => {
const { content } = request.body;
const { id } = request.params;
const contact = {
name: content.name,
number: content.number,
};
Contact.findByIdAndUpdate(id, contact, { new: true })
.then(updatedContact => {
response.json(updatedContact);
})
.catch(error => next(error));
});
app.delete('/api/persons/:id', (request, response) => {
const { id } = request.params;
Contact.findByIdAndDelete(id)
.then(result => {
response.status(204).end();
})
.catch(error => next(error));
});
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const URI = process.env.MONGODB_URI
console.log('connecting to', URI)
mongoose.connect(URI)
.then(_result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})
const contactSchema = new mongoose.Schema({
name: {
type: String,
minlength: 3,
unique: true,
required: true,
},
number: {
type: String,
minlength: 8,
required: true,
}
})
// Apply the uniqueValidator plugin to contactSchema
contactSchema.plugin(uniqueValidator)
contactSchema.set('toJSON', {
transform: (_document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
},
})
module.exports = mongoose.model('Contact', contactSchema)
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
