-
-
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(); | |
}); | |
}); |
Thanks!
When I execute this code I get an error on line 22 stating, "db.collection is not a function" - any ideas what's causing this?
MongoClient.connect API changed from mongoDB version > 3.x, thus I modify the connect method as below, now everything works fine.
MongoClient.connect(connectionUrl, function(err, client) {
console.log("Connected correctly to server");
var db = client.db('myproject');
// 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!");
}
client.close();
});
});
I struggled with the change in the way a database was returned for a while, after digging around for some ways to manage the syntax I produced the following that works well, however I'm using the assert module which needs to be installed on your project by npm, and the database object is now a const.
I'd be interested to know best practice
here:
`//require the mongoClient driver for nodejs from mongodb module
const MongoClient = require('mongodb').MongoClient;
//const assert = require('assert');
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
//mongodb configs if it does not exist its automatically created
var sampleCollection = 'chapters';
//We need to insert these chapters into mongoDB
var chapters = [{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
},{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
}];
// Use connect method to connect to the server
MongoClient.connect (url, function(err, client)
{
assert.equal(null, err);
const db = client.db(dbName);
console.log("Connected successfully to server");
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!");
client.close();
}
});
});`
it don't work until DB receive name
that's work:
`
//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");
var dbo = db.db("mydb");
// Get some collection
var collection = dbo.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();
});
});
`
Works for me now... sharing if anyone of you still stuck.
//require the mongoClient from mongodb module
const MongoClient = require('mongodb').MongoClient;
//mongodb configs - for mongodb nodejs 3.x driver only
//tested with mongoDB v2.6.12 & nodejs v8.11.2
const connectionUrl = 'mongodb://localhost:27017/';
var sampleCollection = 'Cars'; //collection aka table
const dbname = 'MyGarage'; //document aka database
//prepare variable for inserting into mongoDB
var cars = [{
'Model': 'CLA180',
'Brand': 'Mercedes Benz'
},{
'Model': 'GLA180',
'Brand': 'Mercedes Benz'
},{
'Model': 'A4',
'Brand': 'Audi'
},{
'Model': '318i',
'Brand': 'BMW'
}];
//mongodb connection intialization, with callback function
MongoClient.connect(connectionUrl, function(err,client) {
if (err) throw err;
console.log("Connected correctly to server");
const col = client.db(dbname).collection(sampleCollection);
// Get some collection
col.insert(cars,function(error,result){
//here result will contain an array of records inserted
if(!error) {
console.log("Success :"+result.ops.length+" cars inserted!");
} else {
console.log("Some error was encountered!");
}
client.close();
});
});
This is my code after some changes.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
//We need to insert these chapters into mongoDB
var chapters = [{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
},{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
}];
// Use connect method to connect to the server
MongoClient.connect(url, {useNewUrlParser: true} , function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
// Insert multiple documents
db.collection('chapters').insertMany(chapters, function(err, r) {
assert.equal(null, err);
assert.equal(2, r.insertedCount);
//here result will contain an array of records inserted
if(!err) {
console.log("Success :"+r.ops.length+" chapters inserted!");
} else {
console.log("Some error was encountered!");
}
client.close();
});
});
Updated code is working:
//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");
var dbase = db.db("myproject");
// Get some collection
var collection = dbase.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();
});
});
First, I'd got an error explaining I used "db.collection" as a function and it isn't. I'd just changed the way MongoClient is used following the crud mongo tutorial (http://mongodb.github.io/node-mongodb-native/3.1/tutorials/crud/), instantiating MongoClient as client object.
After that, I'd got 2 deprecation warnings: URL parser is deprecated and collection.insert is deprecated. I'd changed the MongoClient instantiation inserting an option ({ useNewUrlParser: true }) and changed .insert to .insertMany. Bellow I pasted a screenshot showing the points I needed to change to make things work.
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();
});
});
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?
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
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
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);
Thanks was useful