access mongodb in nodejs Node.js
To access a MongoDB database in Node.js, you can use the mongodb
library, which is the official MongoDB driver for Node.js. Here's an example of how to use mongodb
to connect to a MongoDB database and perform a simple CRUD operation:
const MongoClient = require('mongodb').MongoClient const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority' const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) client.connect(err => { if (err) { console.error(err) return } // specify the collection and perform an insert operation const collection = client.db('test').collection('users') collection.insertOne({ name: 'John', age: 30 }) .then(result => { console.log(result) }) .catch(err => { console.error(err) }) .finally(() => { client.close() }) })
In this code, we first define the connection URI for our MongoDB database, which includes the username, password, cluster, and database name. We then create a new MongoClient
object and use it to connect to the database. Once the connection is established, we specify a collection and perform an insert operation. We then display the results in the console and close the connection.
Note that mongodb
supports a variety of CRUD operations, as well as aggregation, indexing, and other features. You can refer to the mongodb
documentation for more information on how to use this library.