This is my code for creating an index and finding the data using MongoDB, but it doesn’t show any output or error.
I already install mongose, mongo-client, plus it does not contain any URL errors. Where did it go wrong?
const MongoClient = require('mongodb').MongoClient;
// Connection URL and database name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'myproject';
// Use connect method to connect to the server
function connectDB(){
MongoClient.connect(url, function(err, client) {
if (err) {
console.error('Failed to connect to the MongoDB server:', err);
return;
}
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection('mycollection');
// Create an index on the 'name' field
collection.createIndex({name: Dev,age : 20}, function(err, result) {
if (err) {
console.error('Failed to create index:', err);
console.log(result);
client.close();
return;
}
// Find all documents where the 'name' field is equal to 'John'
collection.find({name: 'dev'}).toArray(function(err, docs) {
if (err) {
console.error('Failed to retrieve documents:', err);
client.close();
return;
}
console.log(docs);
client.close();
});
});
});
}
connectDB();