Skip to content

Instantly share code, notes, and snippets.

@mithunsatheesh
Forked from alecslupu/chapter-02.js
Last active March 1, 2024 21:39
Show Gist options
  • Save mithunsatheesh/8adad40b059866e892ed to your computer and use it in GitHub Desktop.
Save mithunsatheesh/8adad40b059866e892ed to your computer and use it in GitHub Desktop.
//require the mongoClient from mongodb module
var MongoClient = require('mongodb').MongoClient;
//mongodb configs
var connectionUrl = 'mongodb://localhost:27017/myproject',
sampleCollection = 'chapters';
//We need to insert these chapters into mongoDB
var chapters = [{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
},{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
}];
MongoClient.connect(connectionUrl, function(err, db) {
console.log("Connected correctly to server");
// Get some collection
var collection = db.collection(sampleCollection);
collection.insert(chapters,function(error,result){
//here result will contain an array of records inserted
if(!error) {
console.log("Success :"+result.ops.length+" chapters inserted!");
} else {
console.log("Some error was encountered!");
}
db.close();
});
});
@nuelmakara
Copy link

This is the updated code that worked for me in case anyone is wondering why the main code above isn't functional. There have been modifications to the MongoDb source codes with some deprecation here and there as highlighted in the above code sample.

//require the mongoClient from mongodb module
var MongoClient = require('mongodb').MongoClient;

//mongodb configs
var connectionUrl = 'mongodb://localhost:27017/myproject',
sampleCollection = 'chapters';

//We need to insert these chapters into mongoDB
var chapters = [{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
},{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
}];

MongoClient.connect(connectionUrl, { useNewUrlParser: true}, function(err, client) {

console.log("Connected correctly to server");
var db = client.db('myproject');

// Get some collection
var collection = db.collection(sampleCollection);

collection.insertMany(chapters,function(error,result){
//here result will contain an array of records inserted
if(!error) {
console.log("Success :"+result.ops.length+" chapters inserted!");
} else {
console.log("Some error was encountered!");
}
client.close();
});
});

@Azim786
Copy link

Azim786 commented Jan 26, 2022

console.log("Success :"+result.ops.length+" chapters inserted!");
^
TypeError: Cannot read property 'length' of undefined

#I am new to mongodb. Someone please suggest how to resolve this error?

@tskxz
Copy link

tskxz commented Aug 17, 2023

console.log("Success :"+result.ops.length+" chapters inserted!"); ^ TypeError: Cannot read property 'length' of undefined

#I am new to mongodb. Someone please suggest how to resolve this error?

change the result.ops.length to result.insertedCount

@tskxz
Copy link

tskxz commented Aug 17, 2023

I needed to create a mongodb atlas database, you can do it for free and create a cluster and you can get the connection by choosing drivers option
image

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://username:password@cluster0.lbynzll.mongodb.net/?retryWrites=true&w=majority";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});

var sampleCollection = 'chapters';

var chapters = [{
	'Title': 'Snow Crash',
	'Author': 'Neal Stephenson'
}, {
	'Title': 'Snow Crash',
	'Author': 'Neal Stephenson'
}];
async function run() {
  try {
    // Connect the client to the server	(optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
    try {
	await client.db("mydb").createCollection("chapters");
        console.log("Collection chapters created succesfully!");
    } catch {
	console.log("Collection chapters already exists!");
    }
    var result = await client.db("mydb").collection("chapters").insertMany(chapters);
    // console.log("Success: " + JSON.stringify(result, null, 4) + " chapters inserted!");
    console.log("insertedIds: " + result.insertedCount);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment