I have been trying to work with mongodb and to insert some data but I am getting an error .
Here is the code .
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Users').insertOne({
name: 'Andrew',
age: 25,
location: 'Philadelphia'
}, (err, result) => {
if (err) {
return console.log('Unable to insert user', err);
}
console.log(result.ops);
});
db.close();
});
The native driver for MongoDB has changed what its .connect() method provides to you in recent versions.
3.0
connectCallback(error, client)
2.2
connectCallback(error, db)
These being how your (err, db) => { ... } callback is defined in the documentation.
The .connect() method provides you a MongoClient instance. Including the database name in the connection address at least doesn't appear to change that.
You'll have to instead use the client's .db() method to get a Db instance with collections.
const dbName = 'TodoApp';
MongoClient.connect('mongodb://localhost:27017/', (err, client) => {
if (err) { ... }
let db = client.db(dbName);
db.collection('Users')...;
});
Related
I have uploaded data to MongoDB by pymongo and I want to retrieve it in my nodeJs. I am writing function like this but it is not working. my collection name is linux_trace and my database name is Linux_Trace_db.
The error is linux_trace is not defined
const mongoose = require("mongoose")
require('dotenv').config();
const URI = process.env.MONGO_URL;
mongoose.connect(
URI,
(err) => {
if (err) throw err;
console.log('Connected to mongodb');
}
);
linux_trace.find(function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)})
The issue with your code is that you didn't define linux_trace as a variable in javascript.
To get access to a model in a mongo database that already has a collection, you can run something like this
const query = function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)};
mongoose.connection.db.collection('linux_trace', function (err, collection) {
collection.find(query).toArray(cb);
});
I got this from this answer: https://stackoverflow.com/a/6721306/3173748
Here is my code
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log('we are connected');
}
var k ='testt';
var collection = db.collection(k);
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
});
and it is is showing this error "Cannot read property 'collection' of null".
The issue is you are directly calling db.collection irrespective of whether db connection is successful or not. You need to check whether there is an error in db connection. db.collection works only when the DB connection is successful. Check below example for better understanding
MongoClient.connect('mongodb://localhost:27017/test',function(err,db){
if(err)
{
console.log(err);
}
else
{
console.log("Connected to db");
db.collection('testt').insert({"doc1":"hello"},function(err,data){
if(err)
{
throw(err);
}
else
{
console.log("sucessfuly inserted");
}
})
How to manage mongodb connections in a nodejs webapp?
The answer of that question is superb. I would like code however to show this. I've tried the following but since it connects async the connection is not ready by the time I want to do my database query. I'm wondering how do others do this?
'use strict';
// database stuff
var mongodb = require('mongodb'); // mongodb drivers
var MongoClient = mongodb.MongoClient; // interface
var url = 'mongodb://127.0.0.1:27017/self';
// generator flow control
var co = require('co');
// database connect function
var dbConnect = function (url) {
// get the db object
MongoClient.connect(url, {
safe: true
}, function (err, db) {
if (err) throw err;
console.log('mongodb connection successful');
return db;
});
};
var db = dbConnect(url);
// generator function with flow control
co(function* () {
console.log('starting db query');
// count documents in collection
var result =
yield new Promise(function (resolve, reject) {
if (err) reject(err);
db.collection('test').count(function (err, res) {
if (err) reject(err);
resolve(res);
});
});
// output number of documents in collection
console.log(result);
});
// more code....
I would like to use the variable db anywhere in my app.
Here maybe one way to reuse the connection.
var myDb;
//reuse connection if already created
function connect(callback) {
if (myDb === undefined) {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) { return callback(err)};
myDb = db;
callback(null, db);
});
} else {
callback(null, myDb);
}
function doDBOperation(err, db) {
// your mongodb operation through db is here
co(function* () { ...
}
connect(doDBOperation);
You can wrap your database connection into promise and wait it in generator
function connect() {
return new Promise((resolve, reject) => {
MongoClient.connect(url, {safe: true}, (err, db) => {
if (err) return reject(err);
resolve(db);
});
});
}
var dbConnection = connect();
co(function* () {
var db = yield dbConnection;
// your code
});
I am trying to connect to MongoDB with user/password , this is what I did so far:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});
Now I am trying to login inside the data base in order to be able to get inside Mongo Database's collections, how can I do that?
Thanks!
You can perform CURD operations like following:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
//here you can perform operation
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
collection.insert(doc1);
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});
This question already has an answer here:
NodeJS Can't Access Variable Inside Callback
(1 answer)
Closed 7 years ago.
I have the following code:
var db;
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(!err) {
console.log("We are connected");
}
db = database;
});
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
And I get the following output:
We are connected
TypeError: Cannot call method 'collection' of undefined
var db;
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(!err) {
console.log("We are connected");
db = database;
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
}
});
Connect method is asyncrone, so your db variable will be initialized much later, then you start using it. Try this code:
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(err) {
// Here, it may be better to interrupt further work in case of error
console.log('fail', err);
return;
}
var db = database;
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
});
EDIT
A full example of nodejs server, taken from here
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get("/", function(req, res) {
db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});