Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Mongodb Insert in NodeJs

Mongodb Insert in NodeJs

Inserting data into MongoDB using Node.js is super straightforward! You can use either:

  1. βœ… The native MongoDB driver (flexible, low-level)

  2. πŸͺ„ Mongoose (ODM – simpler and schema-based)

Let’s see how to do both πŸ‘‡


βœ… 1. Using Native MongoDB Driver

πŸ“¦ Step 1: Install MongoDB Driver

bash

npm install mongodb


🧾 Step 2: Insert Data

js

const client = new MongoClient(uri);async function insertData() { try { await client.connect(); const db = client.db('myDatabase'); const users = db.collection('users'); // Insert one document const resultOne = await users.insertOne({ name: 'Alice', age: 25 }); console.log('Inserted One ID:', resultOne.insertedId); // Insert multiple documents const resultMany = await users.insertMany([ { name: 'Bob', age: 30 }, { name: 'Charlie', age: 28 } ]); console.log('Inserted Many IDs:', resultMany.insertedIds); } catch (err) { console.error(err); } finally { await client.close(); }}insertData();


πŸͺ„ 2. Using Mongoose (Schema-based)

πŸ“¦ Step 1: Install Mongoose

bash

npm install mongoose


🧾 Step 2: Insert Documents

js

const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected to MongoDB!')) .catch(err => console.error(err));// Define schemaconst userSchema = new mongoose.Schema({ name: String, age: Number});// Create modelconst User = mongoose.model('User', userSchema);// Insert oneconst user = new User({ name: 'David', age: 22 });user.save().then(() => console.log('One user inserted'));// Insert manyUser.insertMany([ { name: 'Eve', age: 27 }, { name: 'Frank', age: 33 }]).then(() => { console.log('Multiple users inserted'); mongoose.disconnect();});


πŸ”₯ Summary

OperationNative DriverMongoose
Insert oneinsertOne({})new User({...}).save()
Insert manyinsertMany([{}, {}])User.insertMany([...])
Auto-create DBβœ… Yes when insertingβœ… Yes when saving

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql