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.
Related
I am from .Net and C# background and I am new to Node.js. I am working on a project, which is mix of MongoDB and Node.JS.
In MongoDB, data from various tools is stored in different different collections. I have to create multiple REST APIs using Node.JS for CRUD operation on that data, these APIs will be called from React.JS application.
I want to keep APIs into separate files for seperate tool and then calling including all files into app.js file.
Please help me with best approach.
For POC purpose, I created a node.js application, where I created app.js file and written all my code for GET|POST|DELETE APIs. This is working fine.
var _expressPackage = require("express");
var _bodyParserPackage = require("body-parser");
var _sqlPackage = require("mssql");
var app = _expressPackage();
var cors = require("cors");
var auth = require('basic-auth');
var fs = require('fs');
const nodeMailer = require('nodemailer');
//Lets set up our local server now.
var server = app.listen(process.env.PORT || 4000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.get("/StudentList", function(_req ,_res){
console.log("Inside StudentList");
var Sqlquery = "select * from tbl_Host where HostId='1'";
GetQueryToExecuteInDatabase(_req,_res, Sqlquery,function(err,data){
console.log(data);
});
});
Don't know exactly what your app intends to do, but usually if you are not serving webpages and your API is not too complex, there is no need to use express. You can build a simple server natively in NodeJS to serve data.
Additionally, if your app has many routes (or is likely to in the future), it is a good idea to put helper functions like GetQueryToExecuteInDatabase() in a separate file outside of app.js such as utils.js.
Based on what I have understood about what you want to do, your file structure should look something like this:
data (db related files)
services (contains one file per api service)
app.js
utils.js
Hope this helps.
I am working on a project that requires a dedicated database per registered user. I prefer working with MongoDB so I'm using that for the same (Am I Right?). The app uses a REST API as the backend (written in Node Express) and an AngularJS App. So, what I think of doing is whenever a user makes a request to some API endpoint say, a GET request to api/user/mydata, I would create a connection to his particular database, fetch the required data, close the connection and return the fetched data as the response. Is this approach correct? Also, I'm using Mongoose as the ODM and PassportJS for user Authentication. Moreover, users of my app are mutually exclusive. There is no data connection between a user with any other registered user.
There's a way to do that but only without using Mongoose. You would have to create a root connection to your MongoDB server (mind it, not to a particular database on that server) using the mongodb node module and then you can switch between the database as per your query requirement without creating a new connection per database as shown below:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// URL to the root of MongoDB Server and not a particular db
const url = 'mongodb://localhost:27017';
// Database Names
const dbName1 = 'myproject1';
const dbName2 = 'myproject2';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db1 = client.db(dbName1);
const db2 = client.db(dbName2);
client.close();
});
You can't do this through mongoose, as mongoose and its models require connection to be made to a particular database and not to just the root db server. Anyways, I didn't want to give up mongoose for my own project so I just had to resort to initializing the db connection and its models per HTTP request by the user and closing the connection upon response.
I want to use a heroku database (already deployed in heroku) for my AngularJS application created using Yeoman. I want to persist my data that is currently an array of JSON objects that goes away when I refresh the page. I am trying to follow Heroku's guide for Node.js here (https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js) but it is very shot, no examples, and I am fairly new to servers/databases. I have a 'web.js' file and the Procfile int my root directories for Node.js and heroku to read that file. I have the "dependencies" already set but I am not sure what is happening in this code below that heroku provides
var pg = require('pg');
pg.connect(process.env.DATABASE_URL, function(err, client) {
var query = client.query('SELECT * FROM your_table');
query.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
First: Where do I put this code?
Second: What is happening here?
and Third: How do I use it to upload my data that is currently an array of JSON objects that I
hardcode into my code into the heroku database?
My web.js file
var gzippo = require('gzippo');
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(gzippo.staticGzip("" + MyApp + "/dist"));
app.listen(process.env.PORT || 9000);
My Procfile
web: node web.js
That code goes in your web.js file.
I'm pretty sure it's accessing your database and setting the results to the variable query so you can access the data.
I think want you want for pushing the data is to look here, particularly at pg:push.
I'm using Windows Azure to deploy a node.js application that I've written that exposes a fairly simple REST CRUD api to clients. Its hosted in a Windows Azure Website and uses MongoDB through the Windows Azure store with mongoose. The requests I'm making to the service are JSON and the responses are JSON (not sure that matters but others have talked about 400 responses to requests with a Content-Type of application/json)
On the first access in a long while, the application returns 400 Bad Request without fail. As long as I keep the application "warm" by hitting it frequently (at least once a minute or so) - I never seem to get this again.
It doesn't matter on the hosting scaling setting - I get the same thing on the free tier as in reserved mode.
Anyone else seen this?
In order to guarantee access to any connection in node.js, you have to put all code that requires a connection inside of the callback. The way that mongoose exposes this connection is through an event. When the event 'open' is called by the mongoose connection, then you have access to a database connection.
I.E.
mongoose.connect('details');
mongoose.on('open', function () {
var connection = mongoose.connection;
// Do things with your connection here
doThings(connection);
});
function doThings(connection) {
app.get(...);
}
It would be helpful if you had a code snippet, but my guess is that your connection to mongo is happening asynchronously and your site is serving the request before the connection is actually open.
I tested this scenario and couldn't reproduce the issue. You can see my code here: https://github.com/ntotten/azure-mongo-sample
Basically, I am using mongoose to connect and the connection is happening right away when the app is loaded. You can see the code below.
app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var TaskList = require('./routes/tasklist');
var taskList = new TaskList(process.env.CUSTOMCONNSTR_MONGOLAB_URI);
...
tasklist.js:
var mongoose = require('mongoose')
, task = require('../models/task.js');
module.exports = TaskList;
function TaskList(connection) {
mongoose.connect(connection);
}
...
I created my Schema's in my models/mymodel.js file. I also have my models in there as well as my methods.
How do I export them into my routes?
// route.js
var mongoose = require("mongoose");
var Posts = mongoose.model("posts")
...
Ensure that you set up a bootstrap mechanism that runs all your model files. Once that is done you should have called mongoose.model("name", Model) for a set of models.
This has cached those models in mongoose internally. So you can just call mongoose.model("name") anywhere you want.
The only thing that's important is order of execution. The model & schemas need to be registered before you run your routes.
This is as a simple as :
// create app
var app = express.createServer(...);
// do stuff with app
var files = fs.readdirSync("models");
files.forEach(function(file) {
require("models/" + file);
});
var routes = fs.readdirSync("routes");
routes.forEach(function(route) {
require("routes/" + route)(app);
});
app.listen(80);
Note that normally readdirSync is evil but it's ok to execute blocking calls at startup time (like require) before your listen to your server
Mongoose creates a singleton when you require() it, and subsequent calls return the same instance.
So as long as you require mongoose when your app inits, then define your models, they will be available in any other file where you require mongoose as described by Raynos.
Unless you want to manage connections to the db server manually, it's also a good idea to call mongoose.connect('...') in your app init; the connection will persist across requests.