Understanding mongoose connections in express.js - node.js

I am learning express.js using the following project:
https://github.com/scotch-io/easy-node-authentication/tree/linking
In server.js I can see and understand the following initiates a connection to the database using the url from database.js:
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
/app/models/user.js contains the following:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
...
}
module.exports = mongoose.model('User', userSchema);
Finally /config/passport.js contains:
var User = require('../app/models/user');
I can see how passport.js obtabs the model from user.js however I am failing to understand how user.js is aware of the connection setup in server.js as the initiated object "mongoose" is not exported?
What am I missing?

as you can see in this file index.js at the last line
var mongoose = module.exports = exports = new Mongoose;
this mean, Mongoosee will export only one instance (singleton) to handler database operations. because you first create connection in your server.js file, after that, any included/require model will have connection to your db server. all app will work on single object.

Related

How does mongoose model connect with mongodb?

I have structured a user collection using mongoose.model().This model exist in seperate file called as model\user.js. The mongodb connection instance (using mongoose) exist in seperate file db\mongoose.js. Both of these files are imported into server.js to work with web application.
var express = require('express');
var bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var app = express();
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var user = new User({
text: req.body.text
});
user.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
The {mongoose} and {User} seems to be a separate entities and model\user.js didn't import ./db/mongoose.js as well . The user model being static content , how does user.save() connects with db and save the document?
First of all let me tell you what is happening in your project.
in Mongoose file:
You have DB connection with Mongoose.
Now Mongoose has your DB connection.
That is the reason it is imported in server.js file.
Secondly, in you model/user.js you have
Declared Schema using Mongoose.
user.save method.
When you use Mongoose here (or any DB related query), it points to your connected DB. Which does not require any explicit connection written in some file.
For more details read Mongoose Docs.
Hope I cleared your thoughts.

Node.js API express web server MongoDB

I'm writing an Node.js REST API using express web server and mongoDB as DB server.
The project's directory tree is the following :
https://i.stack.imgur.com/LFWGt.png
When I try to access "/new/test" route, I'm getting the error "Cannot GET /new/test". By accessing this path it should create an new entry into the DB based on "firstname" URL parameter.
Routes.js :
'use strict';
module.exports = function(app) {
var americaine = require('../controllers/americaineController');
// Firstname Routes
app.route('/new/:firstname')
.post(americaine.new_firstname);
};
DB entry creation function is located on Controller.js :
'use strict';
var mongoose = require('mongoose'),
Firstname = mongoose.model('Firstname');
exports.new_firstname = function(req, res) {
var new_firstname = Firstname(req.params.firstname);
new_firstname.save(function(err, firstname) {
if (err)
res.send(err);
res.json(firstname);
});
};
Model.js :
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstNameSchema = new Schema({
/*id: {
type: Number,
required: false
},*/
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Firstname', FirstNameSchema);
Do you guys have any ideas about my issue ? Thanks in advance.
Jérémy
change the method .post() to .get()
since you're actually doing a get request and not a post request.

Connect my application (node, express, mongo) with my local database and query it

I build a small application with node.js, express.js, passport.js and mongodb. I'm new to this technology so I'm trying to test it locally before uploading the code on a server and connect it with mongolab. Now my problem is that I'm not able to see or query all my user locally with my mongo shell, so, everytime I add a user, I'm not able to see if I really add it or not. So far my code is the following:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
database.js (config/database.js)
module.exports = {
url: 'mongodb://localhost/expressauth',
};
user.js (models/user.js)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = mongoose.Schema({
local: {
name: String,
email: String,
password: String,
},
});
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
module.exports = mongoose.model('User', userSchema);
The code is working fine so far, and every time I add a new user I'm able to obtain a user id (something like that 59397add4905d20f0329125c) and a password.
Now I'm trying to see all my users through the mongo shell so I type MONGO in my terminal and then I type SHOW DBS, so I can see all my database.
I can find the database that I create through my database.js (url: 'mongodb://localhost/expressauth') called expressauth, so I switch to it (USE expressauth) and at the very end I try to make a query (something like SELECT * in mysql) with this method that I found in the documentation => db.expressauth.find().
But I don't receive any data. So I'm not able to test my application (which is actually an web app that I found on github: https://github.com/danielgynn/express-authentication/.
Any suggestion why my mongoshell is not working?
If you're in the mongoshell and already called use expressauth, then you should be able to do show collections to see what collections are in that database. The user or users collection should be there depending on your configuration. Then you can call db.users.find() to get all the users in the collection.

Connect multiple mongo db database in node js using mongoose

I am using mongoose for mongo db connections in node js. Can anyone tell me how can I connect multiple databases in node js. Also please make sure that you have tried that method yourself. Thanks.
Edit: I want to connect to multiple DBs dynamically. Also I don't want multiple models and I have just one project, not various sub-projects.
i believe you are connecting to mongoDB from main entrypoint as index.js or server.js , where you are initiating router. like this
`
const mongoose = require('mongoose')
// mongoose
mongoose.connect("mongoDB url");
const connection = mongoose.connection;
connection.on('open',()=>{
console.log(" database connected")
})
connection.on('error',()=>{
console.log("error in connecting to database")
})
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//middlewares`
in same way you can also connect to different databases directly schemas. like in my use case , i wanted to store users in defferent database and posts in another DB .
the in my app.js , i will connect to main DB as normal connection (above) and for user schema , i will connect to my user DB . like this
const mongoose = require('mongoose');
const connection = mongoose.createConnection("mongo url ");
const userSchema = mongoose.Schema({
name: String,
date_of_birth: Date
})
module.exports = mongoose.model('User', userSchema);
you can also use mongoose.connect() instead of mongoose.createConnection()
hope this helped you.

Getting mongoose not defined error in model file

mongoose module already installed also included in index.js
In index.js
mongoose = require('mongoose').connect(config.dbURL),
...
require('./routes/routes.js')(express, app);
In routes.js
var Category = require('../models/category');
...
Within model folder category.js
var categorySchema = mongoose.Schema({
category_name:String,
alias:String,
added_on:String
});
but error occurred while using in model file.
Folder structure:
server
-> index.js
-> routes/routes.js
-> models/category.js
Please add this line in category.js pages top :
var mongoose = require('mongoose');

Resources