I have mongodb setup locally and I created a database with a collection couples. I verified this using mongosh:
This is the code that connects to the database:
databaseConfig.ts
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/memory-box';
export const client = new MongoClient(uri);
export async function connectToDatabase() {
try {
await client.connect();
console.log('Connected to the database');
} catch (error) {
console.error('Error connecting to the database:', error);
}
}
This is how I use it:
server.ts
async function startServer() {
try {
await connectToDatabase(); // Connect to the database
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
} catch (error) {
console.error('Failed to start the server:', error);
}
}
startServer();
This is the function that creates a couple:
coupleService.ts
export async function createCouple(name1: string, email1: string, name2: string, email2: string): Promise<CoupleType> {
try {
const newCouple = new Couple({
name1,
email1,
name2,
email2,
});
const savedCouple = await newCouple.save();
return savedCouple;
} catch (error) {
throw new Error(`Failed to create couple: ${error.message}`);
}
}
This is the couple model:
Couple.ts
import mongoose, { Model } from 'mongoose';
import coupleSchema from '../schemas/coupleSchema';
import { CoupleType } from '../types/coupleTypes';
const Couple: Model<CoupleType> = mongoose.model<CoupleType>('Couple', coupleSchema);
export default Couple;
This is the couple schema:
coupleSchema.ts
import { Schema } from 'mongoose';
const coupleSchema = new Schema(
{
name1: {
type: String,
required: true,
},
email1: {
type: String,
required: true,
match: [/^S+@S+.S+$/, 'Please use a valid email address.'],
},
name2: {
type: String,
required: true,
},
email2: {
type: String,
required: true,
match: [/^S+@S+.S+$/, 'Please use a valid email address.'],
},
},
{
timestamps: true,
}
);
export default coupleSchema;
When I use postman to create a couple it logs this:
Connected to the database
Server is running on port 3000
???? ~ createCoupleHandler ~ req.body: {
name1: 'John Doe',
email1: '[email protected]',
name2: 'Jane Doe',
email2: '[email protected]'
}
???? ~ createCoupleHandler ~ error: Error: Failed to create couple: Operation `couples.insertOne()` buffering timed out after 10000ms
I’m not sure what’s going on. It seems to be connecting to the database properly but unable to create the couple.
I tried to access the couple collection manually and insert the document and it works:
export async function connectToDatabase() {
try {
// Connect to the MongoDB server
await client.connect();
console.log('Connected to the database');
/** DEBUGGING THE BUFFER ISSUE */
// List all collections in the connected database
const database = client.db();
const couplesCollection = database.collection('couples');
// Insert a couple into the couples collection
const result = await couplesCollection.insertOne({
name1: 'John Doe',
email1: '[email protected]',
name2: 'Jane Doe',
email2: '[email protected]',
});
console.log('Inserted couple:', result.insertedId);
// Find all couples in the couples collection and log them
const allCouples = await couplesCollection.find().toArray();
console.log('All couples:', allCouples);
const collections = await database.listCollections().toArray();
console.log('Collections:', collections.map(collection => collection.name));
} catch (error) {
console.error('Error connecting to the database:', error);
}
}
So I think the Couple model in the service isn’t accessing the database instance or something like that.
Any idea what’s going on?