mongo query by object id node js

To query a MongoDB collection using an ObjectID in Node.js, you can follow these steps:

  1. Import the required modules:
const { MongoClient, ObjectID } = require('mongodb');
  1. Set up the MongoDB connection:
const url = 'mongodb://localhost:27017';
const dbName = 'yourDatabaseName';

MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
  if (err) {
    console.error('Failed to connect to the database:', err);
    return;
  }

  const db = client.db(dbName);
  // Continue with the query here
});
  1. Define the ObjectID you want to query:
const objectId = new ObjectID('yourObjectId');
  1. Perform the query using the ObjectID:
db.collection('yourCollectionName').findOne({ _id: objectId }, (err, result) => {
  if (err) {
    console.error('Failed to query the collection:', err);
    return;
  }

  console.log('Query result:', result);
  // Handle the query result here
});
  1. Close the database connection:
client.close();

Note: Make sure to replace 'yourDatabaseName', 'yourCollectionName', and 'yourObjectId' with the actual values corresponding to your MongoDB database, collection, and ObjectID.

These steps will allow you to query a MongoDB collection using an ObjectID in Node.js.