I made this node js app and then i tried with postman but every time i made a request that involves mongodb, it keeps loading. The function find of the model is where the code stops and the callback is never called.
app.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
//Connection to DB
mongoose.connect('mongodb://localhost:27017/users', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var models = require('./models/user')(app, mongoose);
var userContoller = require('./controllers/user');
var router = express.Router();
router.get('/', function(req, res) {
console.log('GET');
res.send("Hello World!");
});
app.use(router);
var users = express.Router();
users.route('/users')
.get(userContoller.findAllUsers);
app.use('/api', users);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
models/user.js
exports = module.exports = function(app, mongoose){
var userSchema = new mongoose.Schema({
userName: { type: String },
password: { type: Number }
});
mongoose.model('User', userSchema);
};
controllers/user.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
//GET - Return all tvshows in the DB
exports.findAllUsers = function(req, res) {
console.log('llega');
User.find(function(err, users) {
if(err) res.send(500, err.message);
console.log('GET /users')
res.status(200).jsonp(users);
});
};
The mongodb server is started through the console but i don't know how to check it.
Thanks!
EDIT:
I made the code easier for me to test and solve the problem.
The code now is this and im not getting the connection to mongodb.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
console.log('error');
});
db.once('open', function() {
console.log('connected');
});
I don't get in the console the error or the connected.
In the mongod console i get some messages saying that a new connection was made. This happens every time i open the nodejs program.
Thanks
I think the problem is that you are giving call back to the mongoose.connect function. In my case i did:
mongoose.connect(url, options)
const db = mongoose.connection
db.on('error', function () { console.log('Cannot Connect to DB') })
db.once('open', function () { console.log('Mongoose Connected to DB') })
Also instead of:
users.route('/users').get(userContoller.findAllUsers);
You may try:
users.get('/users', userController.findAllUsers);
And I realized that you don't pass a next argument to your controller which express generally complains if you dont pass.
Edit: I think i found the error.
When you are using the .find function you need to pass 2 arguments. In your case because you are not passing the callback as the second argument it never gets called.
User.find({}, callback) should do it.
I found the problem.
The version of mongoose was older than the needed to connect to my mongodb version. Just update it via npm and good to go.
Related
Here is the code example:
app.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
db/conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I've done some research and it stands for 'Database Owner' in SQL Server but it doesn't make sense here.
These code examples are from MongoDB official documentation and why do they assign connection instance as dbo if it really stands for Database Owner?
As the documentation provides no explanation for the choice of variable name, we can only guess. My best guess is that dbo stands for database object, considering the type of the export.
I think this is idiosyncratic usage mimicked from the SQL world where dbo is the default schema and abbreviates database owner.
Typically, and in the MongoClient documentation, I see just db = require("./db/conn"); But it appears here that the author's fingers are just used to automatically typing an o after typing db.
Humans are habitual imitators. I wouldn't think too much of it. It's just a variable name.
There is no restriction and built-in parameters name in nodejs.
You can use that according to your preference
I am trying to connect my school project to a mysql database but I always get the error "TypeError: connection.connect is not a function". I am not quite sure how to fix it. I hope someone is able to solve this.
My index.js
const express = require('express');
const app = express();
var connection = require('./database');
app.use(express.static('public'));
app.get('/form', (req,res) =>{
res.sendFile(__dirname + '/public/index.html' );
console.log(req.url);
console.log(req.path);
})
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection.connect((err) => {
if(err) throw err;
console.log("Connected");
})
});
my database.js
let mysql = require('mysql');
module.exports = () => {
return mysql.createConnection({
host: 'localhost',
database: 'minigames',
user: 'root',
password: 'root'
})}```
connection is the value exported from the database module.
The value you assigned to module.exports there is a function that you defined.
It is a plain, ordinary function and you have no assigned a connect property to it.
I'm guessing that connect is a property on the return value of mysql.createConnection, but if you want to access that object then, you need to call the function you defined in order to get that object.
const express = require('express');
const app = express();
var connection = require('./database');
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection().connect((err) => {
if(err) throw err;
console.log("Connected");
})
});
I am new to mongodb, I am using Express, Body-Parser and Mongoose and I have a mongodb database (its online, its call mlab) where i pull data from. Every thing is working fine, i have used postman to Get, Post and Delete. I am trying to get the data in JavaScript so i can display in the html. I am using Ajax, it works and returns success, but fires the fail function of the Ajax.
exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
if (err) return next(err);
res.send("../Views/images", {photo: photoalbum});
});
};
The mongodb model
const mongoose = require('mongoose');
const Schema = mongoose.Schema,
let PhotoAlbumSchema = new Schema({
title: String,
albums:[
{
u_name: String,
u_title: String
}]
},{
timestamps: true
});
PhotoAlbumSchema.virtual('pictureId').get(function(){
return this._id;
});
The mongodb route
const express = require('express');
const router = express.Router();
//
// Require the controllers
const photoalbum_controller =
require('../controllers/photoalbum.controller');
//
router.get('/find', photoalbum_controller.photoalbum_all);
The app.js
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const photoalbum = require('./routes/photoalbum.route'); // Imports routes for the photos
//
const app = express();
//
// Set up mongoose connection
const mongoose = require('mongoose');
let dev_db_url = 'mongodb://Trex_son:Salvat1on1987#ds243254.mlab.com:43254/photoalbumdb';
let mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/photoalbums', photoalbum);
let port = 1234;
app.listen(port, () => {
console.log('Server is up and running on port number ' + port);
});
I'm not sure Ajax is the best way to retrieve this data, is there any better to retrieve this values to the html
I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.
Here is my code:
dbtest.js
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
var Todo = mongoose.model('Todo', {
text : String
}, 'test');
var status = {
"status": "not connected"
};
app.get('/api/todos', function(req, res) {
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
{
if (err) {
res.json(status);
} else {
res.json('Connected');
}
});
});
app.listen(8080);
console.log("App listening on port 8080");
When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.
I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.
Any suggestions are appreciated.
Your first mongoose.connect() argument lacks username / password combination:
mongoose.connect('mongodb://username:password#127.0.0.1:27017/exampleDB');
Try to connect db first before doing any action. Once it connected try to use inside your custom function. Below code will helps you to test local database
const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
console.log('Connected to database ');
});
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
Check your cmd window to see console.
For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :
mongodb://USER:PASSWORD#127.0.0.1/DB?authSource=admin
You don't need to provide the port 27017, because it's the default one for mongodb.
The trick here is to add with 'authSource=admin' for enabling the authentication.
Documentation :
https://docs.mongodb.com/manual/reference/connection-string/#examples
already tried a lot of tutorials, but somehow I could not figure it out.
I am using mongodb and express.js
this is in my server.js
const express = require('express');
const subdomain = require('express-subdomain');
const bodyParser= require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const routes = require('./routes');
const app = express();
var db;
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('views'));
app.use(subdomain('api', routes.api));
MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
db = database;
app.listen(3000, () => {
console.log('listening on 3000');
});
});
and this is in my routes.js
const express = require('express');
const api = express.Router();
api.get('/', function (req, res) {
db.collection('test').find().toArray((err, result) => {
if (err) return console.log(err);
res.render('api_orders', {test: result});
});
});
module.exports = {
api
}
I would like to use the db variable also in routes, but it always gives me the db is not defined error (obviously) I read that I should somehow export the db var, but could not managed to do it
Instead i would suggest you to create another file and you just require it where you want to use it. Suppose:
db.js:
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
return database;
});
}
module.exports = db;
Now you can use the db anywhere when you do :
const mydb = require('./db'); // <--require it to use
It may not work as it is not tested but it can give you idea to get through.
This is as much a question as a response. I've used
MongoClient.connect('mongodb://localhost:27017/test', (err, database)={
global.bigdb = database
});
and called it from the routes for instance
var col = global.bigdb.collection('collectionname');
Is this bad practice? Rereading the code - it's been live for a while - I'm also exposing the redis client as a global.
Any info appreciated. Live with no bug reports but very curious if I should refactor.
app.use(function(req,res,next))
{
res.locals.yourvariable = null;
next();
});
This is how I initialize global variables. Hope you get an idea.