How to use MongoDB with mean.io - node.js

I am new to server side javascipt. I have started with mean.io. I gained some understanding of nodejs, express, mongodb last few days. I have my mean.io app but I don't know what's the right way to connect to mongodb and query it from my js files.
Is there a guide/blog which can help me work with mongodb from my server side javascript files?
All I want is to store some data mongodb and fetch that at some later point.

By default, you should see there is a mean-dev collection in your mongodb. The best way I thought to get familiar with mongo and mean is play around the code (for instance, the article package). Inside /packages/article/system/, you will see how the blog example works.
That works great for me.

I couldn't find one related to mean.io but below 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:
Past few days I have been working on it and by test & learn I was able to got things working for me. I'll share whatever I know till now.
So mean.io use mongoose ODM to connect to the mongodb.
mean.io would automatically connect to your DB. You can configure DB name in development.js db: 'mongodb://localhost/myDB'. So you won't have to worry about connecting to mongoDB. You just need to start the mongoDB using mongod.
How to use mongoose?
To use mongoose to connect to mongoDB you need to build schemas. You can do so in myApp/app/models directory, since they represents 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 would be stored as tbl_userS in DB.
How to save data to mongoDB?
One would generally do save to DB in controller. Below I have shown how one can do this.
To make models available to all controller one need to write this piece of code in server.js so that all your models get registered during server startup. Alternatively, import individual models using 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 would create and update the tbl_users collection in mongoDB.

Related

How can two different Node.js servers communicate to one mongoose schema?

I have two servers (Public server and Admin Server) and I would like to access from both one mongoose schema. The main server is the Public one where everything happens, but sometimes, from Admin server I would like to access that schema. I could write the schema on both the servers, but that would mean bad code. If that is the only solution, I will do it. But, is there any other way of doing this? For MongoDB I have a third server, that is only for database. Could I write something there so that when I connect with mongoose to the MongoDB server to receive the model from there?
Let's say I have this code (somewhere, I don't know where yet).
const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
title: {
type: String,
required: true,
}
});
const Post = new mongoose.model('Post', postSchema);
module.exports = Post;
What I am trying to do in a server file is for example to call Post.save() or whatever function I am trying to get, without having the schema on both servers.
I used Mongoose-Gen npm and created an API in order to get the schema from on server to another.

Why do we import Mongoose in the Express server file?

I have a Node/Express app that uses Mongoose to talk to a MongoDB database. The Express server is configured in a file called server.js and the schema is in a separate models.js file. Following every project and tutorial I've seen so far, I have the mongoose.connect() configured in both places:
// server.js
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://127.0.0.1/mydb');
// models.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
username: String,
password: { type: String, select: false },
name: String,
});
module.exports = mongoose.model('User', User);
My question is, since I'm already importing mongoose in models.js, can I not skip doing so in server.js entirely and just set the connection in the model script itself? What's the point of importing it and configuring a connection along with the rest of the server config when I'm only going to use it when working with the schema? And If the answer is yes, why doesn't anyone do that? Is there a performance benefit at play here?
You could do mongoose.connect() in your model script but this would not be advisable.
You would have to ensure that this model was loaded before any other scripts that required the mongoose connection.
If you go on to create another model in your application, then this would rely on your User model (model.js) having been loaded first.
You would have to perform the connection in each model just to be sure, but this would be a poor design and unnecessary code duplication.
Therefore, connecting in server.js is the best approach to ensure the connection is established as early as possible.
It is not necessary that you require the mongoose in the server.js file. In fact in my project I create a separate file for each connection like connection_one.js, connection_two.js and export the mongoose object. This way when any number of models does a require("./connection_one.js") it will return the same connection ready mongoose for all models exporting it. This is possible due to modules are cached on first time load inside a project. It is what is also happening when you are loading the mongoose module in server.js, it is the same mongoose object in server.js and model.js.
To address you question, first of all you need to understand object-oriented programming. Right now, you have two different files. One if server.js. and another is models.js. And each file has it's own scope.
Even if you imported mongoose in server.js since the two scopes has different scope set, models.js cannot utilize the mongoose service imported in server.js. For example, let say you defined a variable "foo",
You cannot use that variable in model.js because their scopes are isolated.
// server.js
const foo = 'bar';
If you want to use only one mongoose imported in a single script and shared by others, you can use global object from Node.js env. Check out the url to know more about this.
node.js global variables?
However, I don't really recommned putting mongoose service in gloabl object. Global scope can be easy at the beginning, but it could be significant scalability problem as your application grows bigger in later time.
Thanks.

Referencing NodeJS MongoDB connection from AngularJS

I'm trying to set up a small development environment consisting of a node.js http server, a mongodb database and frontend in angular.js. For development purposes I've created an account with MongoHQ and can reference my db using a URL.
The issue I'm faced with is that I can easily connect to my db from my Angular code but then my connection info is exposed through my http server.
So what I would like to be able to is to create my connection in my NodeJS server.js file and reference it from eg. my AngularJS app.js file. Is that possible and if so how?
Thanks in advance
Try using express and mongoose.
Server side code
var express = require('express');
var app = express();
//start server with port of choice here
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Foo=mongoose.model('foo');
//foo is a model. Check mongoose documentation from collections and schemas
app.get('/hello', function(req, res){
//get data from mongo using mongoose
foo.find({},function(err,docs){
//do stuff here
res.send(docs)
})
});
Front end code
$http.get('/hello').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
//data is the data from mongodb
})
Follow this tutorial to get an idea
There is a stack called MEAN Stack. See if it fits your needs. Very easy to set up and develop.

How to connect to monogodb using monk?

I am building a nodejs app using expressjs framework. I would like to ask how do we connect to mongodb using monk? i found this code online however it seems that we do not need to specify username and password. why is that so?
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
Appreciate any advice.
There are two methods of passing username/password:
// first:
var db = monk('USERNAME:PASSWORD#localhost:27017/nodetest1');
// second:
var db = monk('localhost:27017/nodetest1', {
username : 'USERNAME',
password : 'PASSWORD'
});
It's not very well documented, but since monk uses mongoskin, you can look here for more information.
I want to add an alternative to the answers above as neither worked for me.
So the way I was able to connect to a mongod --auth instance was:
1.Make sure you create a user while logged into mongodb as a user with appropriate permissions to create users on databases (like a user with the role userAdminAnyDatabase). If you don't have a user with this role restart mongo with just mongod without --auth and login as your superuser (if you have one) or with a simple mongo command and make this user with the appropriate privileges.
I highly recommend reading up on mongodb roles here: http://docs.mongodb.org/manual/reference/built-in-roles/
2.Once you are logged into your database instance with the appropriate user who is supposed to be creating other users, type use db_name where db_name is the name of your database that you want to make the user for.
3.Once inside this database use the db.createUser command like so: db.createUser({user:"your_username", pwd:"your_password", roles:["your_role"]})
It's documented here: http://docs.mongodb.org/manual/reference/method/db.createUser/
4.Then just use db = monk('USERNAME:PASSWORD#localhost:27017/DATABASE_NAME') in your code.
After you've done this you should be able to log into a running mongod --auth instance with a user for the particular database you created that user for.
For anyone curious I'm developing a little web app in Koa. Using monk and co-monk.
In apps.js:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
In /lib/mylib.js:
var db = require('../apps.js')
Though i would recommend making a separate file called db.js and in that file export the connection ,that is more cleaner.

How could I know if the mongodb is started or not by mongoose?

I have a working site with node.js + Express + mongoose.
I am afraid there will be chance that the MongoDB will be shut down by accident or maybe it wasn't started at first.
The following is the code:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/Test');
var Student = mongoose.model('student', new Schema());
Student.find({...},function(err,docs){
do sth
});
As I see , there will be no err message when find in no Mongo situation. It was just blocked.
And I didn't find a property in mongoose to show the connection status.
So anyone know how could I know the status of the mongodb in NodeJs?
The err parameter is a standard Error object which will be set if there any exceptions such as the database connection being unavailable. You do not need to check the connection status .. you need to check err and handle appropriately.
It would be worth having a read of the introduction to MongoDB's node driver for some example usage.
See also Error handling for Mongoose.

Resources