How to use MongoDB with average.
I am new to javascipt server side. I started with mean.io. I've gotten some understanding of nodejs, express, mongodb in the last few days. I have my mean.io application, but I don't know how to properly connect to mongodb and request it from my js files.
Is there a tutorial / blog that can help me work with mongodb from javascript server side files?
All I want is to store some mongodb data and retrieve it at some later point.
source to share
I couldn't find one related to mean.io, but below a few links helped me get started with mean.io.
http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
https://www.youtube.com/watch?v=AEE7DY2AYvI
https://www.youtube.com/watch?v=5e1NEdfs4is
Edit:
Over the past few days I've been working on this, testing and finding out that I've managed to get everything to work for me. I will share what I know so far.
- So mean.io uses
mongoose
ODM to connect to mongodb. -
mean.io
will automatically connect to your DB. You can customize the database name indevelopment.js
db: 'mongodb://localhost/myDB'
. So you don't have to worry about connecting to mongoDB. You just need to start mongoDB withmongod
.
How to use mongoose?
To use mongoose
to connect to mongoDB you need to build schematics. You can do this in the directory myApp/app/models
as they represent the models.
Sample Model File user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
email: String,
DOB : Date,
address: {
house_no: String,
street: String
}
});
module.exports = mongoose.model('tbl_user',userSchema);
Note. - tbl_user
will be stored as tbl_userS
in the database.
How to save data to mongoDB?
Typically save
for a DB in a controller. Below I have shown how this can be done. To make models available to all controllers, you need to write this piece of code in server.js so that all your models are registered when the server starts up. Alternatively, import individual models with require('tbl_user')
.
Server.js
: -
var models_path = __dirname + '/app/models';
var arrFiles = fs.readdirSync(models_path);
arrFiles.forEach(function(file){
if(file.indexOf('.js') > 0){
require(models_path + '/' + file);
}
});
controller code myApp/app/controllers/myController.js
var mongoose = require('mongoose');
var jsonEntry = {'name':'Mady', 'email':'xyz@xyz.com', 'address':{'house_no':12N, 'stree':'abc'}};
var User = mongoose.model('tbl_user');
var user = new User(jsonEntry);
user.save();
The above code will create and update the collection tbl_userS
in mongoDB.
source to share