MongoDb and Node.js - node.js

so I am working with node.js and mongodb and I am a rookie
The below us my code:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url,function(err,db){
if (err){
return console.dir(err);
}
console.log('connected to mdb');
InsertDoc(db,function(){
db.close();
})
});
const InsertDoc= function(db, callback){
const collection = db.collection('users');
collection.insert({
name : 'vishnu',
email:'vishnu#123'
},
function(err,result){
if(err){
return console.dir(err);
}
console.log('inserted doc');
console.log(result);
callback(result);
});
}
ERROR: TypeError: db.collection is not a function
I am not sure where I have gone wrong
kindly let me know the mistake

The callback from connect will return you an instance of MongoClient and an instance of Db, as mentioned in official Mongodb Node driver documentation, look at the second example
https://mongodb.github.io/node-mongodb-native/4.1/classes/MongoClient.html
Once you obtain the collection you will have to get the db by using client.db(dbName) which will give you the db object for creating a collection.
// Connect using the MongoClient.connect static method
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017/myproject';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
const db = client.db("myproject");
const collection = db.collection("users");
// do your thing
client.close();
});
`

Related

Retrieving data from mongodb stored by pymongo

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

Problems returning database information with MongoDB, Node.js and Express

const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myorders';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("The connection was awesome");
const db = client.db(dbName);
second.get('/Students',(req,res) => {
const findStudents = function(db,call) {
const collection = db.collection('Students');
collection.find({}).toArray(function (err,result) {
if (!err) {
res.send(result)
} else {
console.log(err);
call(err);
}
});
}
});
client.close();
});
second.listen(3200,() => {
console.log('We got it running');
});
module.exports = second;
So I am trying to display my mongodb information on a web server and here are the screen shots
Above is the MongoDB collection of students and marks
And above is my Node.js command prompt and I get a deprecation warning. Is there any way I can fix it? Is there any other error why I can't display the information in the web server?
To fix this deprecation warning, all you need is to do what it says: pass the option useNewUrlParse: true in the options object to MongoClient.connect. So the line where you connect to MongoDB database would be:
MongoClient.connect(url, { useNewUrlParse: true }, function(err, client)
Anyway, this is just a warning, not a blocking error, and your app is running. I think there are several things wrong in your code, mainly that you declare the function to be executed on the GET to /Students within the callback of the connection to the database and that you close that connection so that the data could no longer be accessed. I think this code should work for you:
const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbUrl = 'mongodb://localhost:27017';
const dbName = 'myorders';
let db;
MongoClient.connect(url, (err, client) => {
assert.equal(null, err);
db = client.db(dbName);
console.log("The connection was awesome");
});
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
});
});
EDIT:
If you think that the database should not be always opened, yous should connect and close at each request to /Students, this way:
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
MongoClient.connect(url, (err, client) => {
if (err) return res.status(500).send(err);
db = client.db(dbName);
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
client.close();
});
});
});

Why is `func` not a function here in node.js?

I am learning mongodb, and in the book, there's a code
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};
I run this code, but throw the error TypeError: func is not a function, I googled, but lots of codes like this, my mongodb version is 4.0, and node.js version is 9.10, any ideas?
Whatever func you are passing must be a function.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) { //func must be function, dont pass just a variable
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};

mongoDB / NodeJS save() method not working

I'm a beginner at NodeJS / MongoDB so maybe it would be easy for you.
I have this simple code :
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird')
MongoClient.connect("mongodb://localhost:27017/db_ldap_users", function(err, db) {
if(err) {
throw err;
}
console.log("connected to the mongoDB !");
});
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});
Here is the output :
connected to the mongoDB !
Service /test called
User created
The problem is the user is never add to the DB. I have never entered in the callback, I don't know why, I have followed multiple tutorial and it seems to always works for them. Does someone has an idea ?
EDIT : I forget to add
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
I was thinking the connection to the Database was enough Thanks
Thanks you
look this:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});

Find result based on id in mongo db using node.js

I want to find result from collection using node.js in mongodb. My code is as follows
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
collection.findOne({_id:req.body.Id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
I am not able to get required result.Getting error collection is not defined.
Try convert id to ObjectId:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
db.collection('collectionName').findOne({_id:new ObjectID(req.body.Id)},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
You need to define which collection you're going to query:
db.collection('CollectionName').findOne({_id: req.body.Id}, function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
db.close();
});
Node.js MongoDB Driver API - findOne

Resources