Nodejs mongodb don't woking on server - node.js

On local, I installed NodeJS 9.2 and MongoDB 3.4
I using MongoDB Native Node Driver 3.0.4
My code with database
const mongo = require('mongodb').MongoClient;
const mongoose = require('mongoose');
mongo.connect('mongodb://localhost:27017/my_database', function(err, client){
console.log(err);
if (!err){
var database = client.db('my_database');
database.collection('users').find({}).toArray(function(err, docs){
console.log(docs);
});
}
});
Result null for error and array users in collection
So, on server centos 7 installed nodejs 8.2, Result null for error and empty array for docs
How does it work?

Connection
const mongoose = require('mongoose');
const URL = "mongodb://user:pass#mongo:27017/database?authSource=admin";
mongoose.connect(URL, {"server":{"auto_reconnect":true}});
var db = mongoose.connection;
db.on('error', function(err) {
console.error('Error in MongoDB connection: ' + err);
});
db.on('connected', function() {
console.log('Connected to MongoDB');
});
Model
You create a schema that represents a collection in your db
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MyModel = Schema({
foo: String
}, { collection: 'mycollection' });
module.exports = mongoose.model('MyModel', MyModelSchema);
Controller
You use this schema to execute requests to that collection
const MyModel = require('../models/mymodel');
function myFunction(req, res) {
MyModel.find({}).exec(function(err, result){
if(!result) return res.status(404).send();
var array = [];
result.map(function(data){
array.push(data.foo);
});
res.status(200).send({"mydata": array});
});
}
module.exports = {
myFunction
};

Related

showing undefined when trying to access the collection using nodejs

i am trying to display all the documents in a collection called tutorial so i am using a simple code here's my code
const mongodb = require("mongodb");
const express = require("express");
var app = express();
var mongoClient = mongodb.MongoClient;
var conn = "mongodb://localhost:27017";
mongoClient.connect(conn, (err, client) => {
if (err) {
console.log(err);
} else {
console.log("connection estableshed");
var db = client.db("mydb");
var collection = db.collection("tutorial");
collection.find().toArray((err, data) => {
console.log(data);
});
client.close();
}
});
but the result i got undefined so what seems to be the problem here?
Problem with the callback, you can use then() method instead.
const mongodb = require("mongodb");
const express = require("express");
var app = express();
var mongoClient = mongodb.MongoClient;
var conn = "mongodb://localhost:27017";
mongoClient.connect(conn).then((err, client) => {
if (err) {
console.log(err);
} else {
console.log("connection established");
var db = client.db("mydb");
var collection = db.collection("tutorial");
collection
.find()
.toArray()
.then((data) => {
console.log(data);
});
client.close();
}
});
app.listen(3000, () => {
console.log("Server started");
});

mongoose save (example from their website not working)

I have my file to add data to mongo via mongoose :
var mongoose = require('mongoose');
var mongoDB = 'mongodb://myuser:mypass#ds145293.mlab.com:45293/employees';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open',function(){
console.log('connected')
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
});
})
mongoose.connection.close()
Copied almost verbatim from mongoose site.I am able to connect to the database but i dont get the 2nd console log.I have a db but no collections.Is this the problem?
Replace mongoose.Schema with new Schema and also I don't think this mongoose.Promise = global.Promise is required.
It cant complete the save before you close the database. There are many options to wait for the save. I like async/await.
edit: sorry that was too quick. Updated example.
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
async function run() {
await mongoose.connect(mongoDB);
console.log('connected')
var kittySchema = new mongoose.Schema({ name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
await fluffy.save();
console.log('saved');
mongoose.connection.close();
}
run();
Or you can just move the close to after you have saved:
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open', function () {
console.log('connected')
var kittySchema = new mongoose.Schema({name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
mongoose.connection.close();
});
})

I am getting empty array as a response when i do get request

I am new to nodejs and express.When i try to do get request from the mongoose database in mlab.com i get an empty response.
my serve code is (app.js),
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var db =mongoose.connect('mongodb://test:test#ds155695.mlab.com:55695/app');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected');
});
var user = require('./model/userModel');
var routers = express.Router();
routers.route('/getUSers').get(function(req,res){
user.find(function(err,users){
if(err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use('/api',routers);
app.listen(8000,function() {
console.log('server working');
});
My model is userModel.js
var mongoose = require('mongoose');
var app = mongoose.Schema({
firstName : String,
lastName : String
});
module.exports = mongoose.model('users',app);
can anyone help me where am i going wrong !

MongoDB-mongoose does not respond to REST API

I have a strange issue with MongoDB-mongoose, which does not respond to REST API
mongoose version - 4.11.3
Mongo DB shell version 3.4.6
Everything is local on my computer
Connection to Mongo DB is the following:
server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
...
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
The log "Connected correctly to db" is printed.
Schema (tasks.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = new Schema({
name: String
});
var Task = mongoose.model('Task', taskSchema);
module.exports = Task;
And finally taskRouter.js
var express = require('express');
var bodyParser = require('body-parser');
var Task = require('../models/tasks');
var taskRouter = express.Router();
taskRouter.use(bodyParser.json());
taskRouter.route('/')
.get(function (req, res, next) {
Task.find({}, function (err, task) {
console.log("result"+task)
if (err) throw err;
res.json(task);
});
})
.post(function (req, res, next) {
var task = new Tasks();
console.log ('the name is '+req.body.name);
task.name = req.body.name;
task.save(function(err){
console.log ("arrived there");
if (err)
res.send(err);
res.json({message: "Task created"});
});
})
As you see, everything is by the book .
But I never get any logs from task.save and Task.find
My 'morgan' logger shows just the following logs:
GET /api/tasks - - ms - -
POST /api/tasks - - ms - -
Postman is stuck on "Loading", until receives a timeout: Could not get any response.
All simple operation on the tasks collection in Mongo DB shell are performed without any problem.
What happens with mongoose?
Thanks in advance.
Try to create a separate file config.js with the following code :
module.exports = {
'database': 'mongodb://localhost:27017/yourdatabasename'
}
server.js:
...
var config = require('./config'); // get our config file
...
var mongoose = require('mongoose');
...
mongoose.connect(config.database, { useMongoClient: true });
mongoose.connection.on('open', function(err, doc){
console.log("connection established");
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});

set mongodb node.js connection once for all routes using mongoclient

I'm new in node.js and mongo db and i have done my code like this in all my routes.
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var ObjectID = mongo.ObjectID;
var collection;
//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
//connection error or success message
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
throw err;
} else {
console.log("connected to the mongoDB");
}
//index
router.get('/', function(req, res) {
collection = db.collection('category');
collection.find({}).toArray(function(err, category) {
collection = db.collection('subcategory');
collection.find({}).toArray(function(err, subcategory) {
collection = db.collection('product');
collection.find({}).toArray(function(err, product) {
collection = db.collection('banner');
collection.find({status: 'A'}).toArray(function(err, banner) {
console.log(banner);
res.render('home',
{
title : 'Home',
categorys : category,
subcategorys : subcategory,
products : product,
banner : banner
}
);
});
});
});
});
});
});
module.exports = router;
please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance
Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.
NodeJS Mongo Driver default connection pool size is 5.
Important: db and categoryCollection variables are kept outside each requests.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
categoryCollection = db.collection('category');
app.listen(3000);
console.log('Listening on port 3000');
});
app.get('/', function(req, res) {
categoryCollection.find({}).toArray(function(err, category) {
});
});
You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
if (err) throw err;
});
and in your routes you can now access MongoDB without having to write any connection code.

Resources