ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Insert in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1401' AND `tutorial_status`=1 LIMIT 1

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