Node JS MongoDB Create


Creating operations in Node.js with MongoDB involve inserting new documents into a MongoDB collection. Here’s how to perform create operations using both the MongoDB native driver and Mongoose, an Object Data Modeling (ODM) library for MongoDB.

1. Using MongoDB Native Driver

1.1 Set Up MongoDB Connection

First, set up your MongoDB connection using the MongoDB native driver.

Installation:

npm install mongodb

Code Example:

const { MongoClient } = require('mongodb'); // MongoDB URI and database name const uri = 'mongodb://localhost:27017'; const databaseName = 'mydatabase'; async function createDocument() { const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { // Connect to the MongoDB cluster await client.connect(); console.log('Connected to MongoDB'); // Get a reference to the database const database = client.db(databaseName); // Get a reference to the collection const collection = database.collection('mycollection'); // Create a new document const newDocument = { name: 'Alice', age: 28, email: 'alice@example.com' }; // Insert the document into the collection const result = await collection.insertOne(newDocument); console.log('Document inserted with _id:', result.insertedId); } catch (error) { console.error('Error:', error); } finally { // Close the connection await client.close(); } } createDocument();

Explanation:

  1. Connect to MongoDB: Create a MongoClient instance and connect to your MongoDB server.
  2. Get Database and Collection: Access the database and collection where you want to insert the document.
  3. Insert Document: Use the insertOne() method to insert a single document.
  4. Close Connection: Ensure to close the connection after the operation is complete.

Alternative Insert Methods:

  • Insert Many: To insert multiple documents at once, use insertMany():

    const documents = [ { name: 'Bob', age: 32, email: 'bob@example.com' }, { name: 'Charlie', age: 25, email: 'charlie@example.com' } ]; const result = await collection.insertMany(documents); console.log('Documents inserted:', result.insertedIds);

2. Using Mongoose

2.1 Set Up Mongoose

Mongoose provides a more structured approach with schemas and models.

Installation:

npm install mongoose

Code Example:

const mongoose = require('mongoose'); // MongoDB URI const uri = 'mongodb://localhost:27017/mydatabase'; // Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(error => console.error('Error connecting to MongoDB:', error)); // Define a schema const userSchema = new mongoose.Schema({ name: String, age: Number, email: String }); // Create a model const User = mongoose.model('User', userSchema); async function createDocument() { try { // Create a new document const newUser = new User({ name: 'David', age: 45, email: 'david@example.com' }); // Save the document to the database const result = await newUser.save(); console.log('Document inserted:', result); } catch (error) { console.error('Error:', error); } finally { // Close the connection await mongoose.connection.close(); } } createDocument();

Explanation:

  1. Connect to MongoDB: Use mongoose.connect() to connect to your MongoDB server.
  2. Define Schema: Create a Mongoose schema that defines the structure of the documents.
  3. Create Model: Use the schema to create a model, which represents a collection in MongoDB.
  4. Create Document: Instantiate a new model object and use the save() method to insert it into the collection.
  5. Close Connection: Ensure to close the connection after the operation is complete.

Alternative Insert Methods:

  • Insert Many: To insert multiple documents, use insertMany():

    const users = [ { name: 'Emma', age: 30, email: 'emma@example.com' }, { name: 'James', age: 29, email: 'james@example.com' } ]; const result = await User.insertMany(users); console.log('Documents inserted:', result);

Best Practices

  1. Validation: Use Mongoose schemas to validate data before inserting it into the database.
  2. Error Handling: Implement proper error handling to manage issues during database operations.
  3. Connection Management: Ensure proper management of database connections, including closing connections when not needed.
  4. Indexing: Consider indexing fields that are frequently queried to improve performance.