insertOne() and insertMany()Inserting records into a MongoDB collection in Node.js uses collection.insertOne() for a single document and collection.insertMany() for batches. If a document omits _id, the MongoDB Node.js driver generates a unique ObjectId automatically and returns insertedId (or insertedIds) so you can link related data right away.
Always attach timestamps (createdAt: new Date()) explicitly in Node.js and handle duplicate-key errors (err.code === 11000) when inserting into collections with unique indexes.
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017');
async function seedProducts() {
try {
await client.connect();
const products = client.db('kodersolution_store').collection('products');
const single = await products.insertOne({
sku: 'KB-101',
name: 'Wireless Mechanical Keyboard',
price: 89.99,
tags: ['peripherals', 'keyboard'],
createdAt: new Date(),
});
console.log('Inserted ID:', single.insertedId);
const batch = await products.insertMany(
[
{ sku: 'MS-202', name: 'Ergonomic Mouse', price: 49.0, createdAt: new Date() },
{ sku: 'HB-303', name: 'USB-C Hub', price: 34.5, createdAt: new Date() },
],
{ ordered: false }
);
console.log('Batch inserted count:', batch.insertedCount);
} catch (err) {
if (err.code === 11000) {
console.error('Duplicate SKU skipped or rejected.');
} else {
throw err;
}
} finally {
await client.close();
}
}
seedProducts().catch(console.error);
{ ordered: true } vs { ordered: false }By default, insertMany() runs with { ordered: true }, stopping immediately at the first error and skipping remaining documents in the array. Passing { ordered: false } tells MongoDB to continue inserting all other valid documents even if one item fails a unique index check.
for loop with await insertOne(): Sequential network round-trips make bulk imports painfully slow. Batch arrays in chunks of 500–1,000 documents using insertMany().req.body directly into insertOne(req.body): Users could inject unexpected fields like role: 'admin' or isPaid: true. Destructure only allowed fields explicitly before inserting.insert() method: Modern mongodb v4+ drivers removed collection.insert(); always use insertOne() or insertMany().insertOne() return in the modern Node.js driver?It returns { acknowledged: true, insertedId: ObjectId(...) } rather than the full inserted document.
_id value?Yes. Passing _id: 'order-2026-001' or a UUID string works fine as long as every _id in that collection remains unique.
Each BSON document can be up to 16 MB. Store large files in S3 or MongoDB GridFS instead of embedding giant binary blobs inside documents.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.