Mongoose connect but doesn't record documents - angularjs

I am working on a MEAN application and I am trying to execute a job every X seconds that updates my DB. But, as first sprint, I am trying to launch a couple of queries just when I start express server (one for populate and another to list). Here is my code:
// set up ========================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
[....]
var Schema = mongoose.Schema;
// configuration =================
// connect to mongoDB database on localhost
var connection = mongoose.createConnection('mongodb://localhost/dv_db_admin');
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
console.info('connected to database dv_db_admin')
});
[...express stuff...]
// define model =================
var CountrySchema = new Schema({
name : String,
icaoCode : String,
documents : [String]
});
var Country = mongoose.model('Country', CountrySchema);
var country = new Country({
name : 'Afghanistan',
icaoCode : 'AFG',
documents : []
});
country.save(function(err, country) {
if (err) console.log("Error:",err);
console.log("Saved:",country);
});
console.log("After save");
Country.findOne({}, function(err, country) {
if (err) console.log("Error:",err);
console.log("Load:",country);
});
console.log("After find");
app.get('*', function(req, res) {
// load the single view file (angular will handle the page changes on the front-end)
res.sendfile('./public/index.html');
});
// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");
When I launch it, I have the following log output:
C:\Mercurial\DV-DB-Catalog>npm start
> dv-db-catalog#1.0.0 start C:\Mercurial\DV-DB-Catalog
> node server.js
After save
After find
App listening on port 8080
connected to database dv_db_admin
As you can see, there is no log about saved or list executions. I've run mongo shell and executed show dbs but it didn't appear.
Anybody knows what's happening?
Thanks in advance!
P.S.: I am running on background mongo service. When I start express server, Mongo log shows the following:
2016-04-15T12:00:50.876+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50766 #71 (3 connections now open)
2016-04-15T12:00:50.877+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50767 #72 (4 connections now open)
2016-04-15T12:00:50.878+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50768 #73 (5 connections now open)
2016-04-15T12:00:50.881+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50769 #74 (6 connections now open)

Try moving all of your calls to MongoDB in the connection.once callback. It looks like you are trying to save/load data from MongoDB before you have connected:
connection.once('open', function () {
console.info('connected to database dv_db_admin')
// define model =================
var CountrySchema = new Schema({
name : String,
icaoCode : String,
documents : [String]
});
var Country = mongoose.model('Country', CountrySchema);
var country = new Country({
name : 'Afghanistan',
icaoCode : 'AFG',
documents : []
});
country.save(function(err, country) {
if (err) console.log("Error:",err);
console.log("Saved:",country);
});
console.log("After save");
Country.findOne({}, function(err, country) {
if (err) console.log("Error:",err);
console.log("Load:",country);
});
console.log("After find");
});

Related

Send Notification properly using Socket.io Redis server

OBJECTIVE: When post is added to perticular channel send notification to all connected subscribed users for that channel.
Relational Database tables over view: Post, Channels, Users, Channels_Users
Post: id, title, content, channel_id(Indicate post is related to what channel)
Channels: id, name (List of Channels)
Users: id, username (User Table)
Channels_Users: id, channel_id, user_id (This table indicate which channels user is subscribed to.)
Goal: When post is created, send notification to perticular user group.
I have tried serveral ways and it is working as aspected. But I am looking for the correct way of doing this.
Server Side: socket.js
Naming conventions:
Channel name:
channel-1, channel-2, channel-3, ....
Namespace name('namespace-'+[channelName]) :
namespace-channel-1, namespace-channel-2, ...
var app = require('express')();
var request = require('request');
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
var Redis = require('ioredis');
var redis = new Redis(####, 'localhost');
// Get all channels from Database and loop through it
// subscribe to redis channel
// initialize namespace inorder to send message to it
for(var i=1; i=<50; i++) {
redis.subscribe('channel-'+i);
io.of('/namespace-channel-'+i).on('connection', function(socket){
console.log('user connected');
});
}
// We have been subscribed to redis channel so
// this block will hear if there is any new message from redis server
redis.on('message', function(channel, message) {
message = JSON.parse(message);
// send message to specific namespace, with event = newPost
io.of('/namespace-'+channel).emit('newPost', message.data);
});
//Listen
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
Client side: Angularjs Socket factory code: (Mentioning main socket code)
// userChannels: user subscribed channels array
// Loop through all channel and hear for new Post and
// display notification if there is newPost event
userChannels.forEach(function (c) {
let socket = {};
console.info('Attempting to connect to namespace'+c);
socket = io.connect(SOCKET_URL + ':3000/namespace-'+c, {query: "Authorization=token"});
socket.on('connect',function(){
if(socket.connected){
console.info("namespace-" + c + " Connected!");
// On New post event for this name space
socket.on('newPost', function(data) {
/* DISPLAY DESKTOP NOTIFICATION */
});
}
});
});
Publish data to Redis server, at the time of new post created
$data = [
'event' => 'newPost',
'data' => [
'title' => $postTitle,
'content' => $postContent
]
];
$redisChannel = "channel-" . $channelId; // As per our naming conventions
Redis::publish($redisChannel, json_encode($data));
The user is getting notification correctly for the channels they have been subscribed.
Problem 1: I am not sure this is the best solution to implement this notification thing.
Problem 2: When a user opens the same application in more than one browser tabs, it gets the notification for all of them. It should send only one notification. This is something related to user management at server side on redis end. I am not sure about this part too.
I really appreciate your suggestion/help on this. Thank you in advance.

How to edit server stored JSON file with NodeJS

I have a web server hosting over localhost. The website I am accessing is a "Todo list app" written with AngularJS. To load the todo's, the browser gets a JSON file with the information. An example of this:
[
{"name":"Clean the house"},
{"name":"Water the dog"},
{"name":"Feed the lawn"},
{"name":"Pay dem bills"},
{"name":"Run"},
{"name":"Swim"}
]
It then loops through all the items and "prints" them out onto the website. I have various options like "Save" and "Delete". They work client-side, but that way does not allow me to properly save them, as when the browser is refreshed, all the content is reset with the server's static JSON file.
I was wondering if there was some way of using NodeJs to host the website and listen for incoming AJAX request and edit the content in the file based off that.
Writing a file asynchronously in nodejs can be done as follows.
var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);
file.key = "new value"; // This will be coming as a http POST method from your view
fs.writeFile(fileName, JSON.stringify(file), function (err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
The caveat is that json is written to the file on one line and not prettified. ex:
{
"key": "value"
}
will be...
{"key": "value"}
To avoid this, simply add these two extra arguments to JSON.stringify
JSON.stringify(file, null, 2)
null - represents the replacer function. (in this case we don't want to alter the process)
2 - represents the spaces to indent.
NodeJS does not persist data out of the box.
You want something like NodeJS + Express and special CRUD routes like POST for creating items or DELETE for deleting them.
In this routes you have to add a data persistance layer like mongoose if you want to use MongoDB or Sequelize if you want to add a SQL database behind it.
Each of this ORM requires to specify a Datamodel which can be saved.
Here an example for a mongoose implementation:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var plugins = require('./model.server.plugins');
/**
* Customer Schema
*/
var CustomerSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill a name',
trim: true
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('Customer', CustomerSchema);
Here is the controller
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Customer = mongoose.model('Customer'),
_ = require('lodash');
/**
* Create a Customer
*/
exports.create = function(req, res) {
var customer = new Customer(req.depopulated);
customer.user = req.user;
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
Here the route
router.route('/')
.post(customers.create);

Cannot find the object "QueryNotificationErrorsQueue" because it does not exist or you do not have permissions

I am using SqlDependecy with signalR to push notifications to client browser when there is some database changes, I followed this and this post and everything works fine in local SqlExpress version 11.0 with Local Connection String , but i have some kind of permissions problem when i connect to remote database hosted in GoDaddy with Production Connection String
Working Local ConnectionString
<!--<add name="NotifyConnection" providerName="System.Data.SqlClient" connectionString=
"Data Source=.\SQLExpress;Initial Catalog=TestDB;Integrated Security=SSPI;" />-->
Production ConnectionString
<add name="NotifyConnection" connectionString="Server=000.00.00.000;Database=TestDB;
User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />
Get Data Method
public IEnumerable<Order> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings
["NotifyConnection"].ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT OrderID,CustomerID FROM dbo.[RestUser]";
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>() // Here the Error throws
.Select(x => new Order()
{
OrderID = x.GetInt32(0),
CustomerID = x.GetInt32(1)
}).ToList();
}
}
}
What i have tried ?
I followed this post to Grant permissions in sql server , but not sure is this correct method to follow.
USE YourDatabaseName;
CREATE QUEUE NameChangeQueue;
CREATE SERVICE NameChangeService ON QUEUE NameChangeQueue ([http://schemas.microsoft.com/
SQL/Notifications/PostQueryNotification]);
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourUserName; // Here i get this error:
//Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema,
sys, or yourself.
ALTER DATABASE YourDatabaseName SET ENABLE_BROKER; // Broker is already enabled
Screen Shot:
I am new to SqlDependency, how to fix this issue ?
Any help would be great.
In shared hosting because they restrict some features, so i was unable to use SqlDependency, but here is my solution to Play notifications without SqlDependency in asp mvc
If you are new signalR, then first try this post to create simple chat web application.
My requirement was to play notifications when new sales happens in shops
1. Create SignalR Server Hub
SignalR server hub class that sends messages to all clients browser.
[HubName("PascalCaseNewSalesHub")]
public class NewSalesHub : Hub
{
public void Send(string shopid)
{
// Call the alertNewSalesToPage method to update clients.
Clients.All.alertNewSalesToPage(shopid);
}
}
2. Javascript Send Method in PlaceOrder View
When a customer places new order for this shop then the following javascript code Calls the Send method on the server hub to update clients.
<script>
$(function ()
{
// Reference the auto-generated proxy for the hub.
var chat = $.connection.PascalCaseNewSalesHub;
var thisShopID = #(ViewBag.ShopID);
// Start the connection.
$.connection.hub.start().done(function () {
// Call the Send method on the hub to send this shops ID
chat.server.send(thisShopID);
});
});
3. Javascript Client Call Back Method in ShopSales View
The hub class on the server calls this javascript function to push content updates to each client.
<script type="text/javascript">
$(function ()
{
console.log('Page loaded');
// Declare a proxy to reference the hub.
var notifications = $.connection.PascalCaseNewSalesHub;
if (notifications != null)
{
console.log('connected to SalesHUB proxy');
}
var thisShopID = #(ViewBag.ShopID);
// Create a function that the hub can call back to alert new sales.
notifications.client.alertNewSalesToPage = function (shopid)
{
// check if sales happened for this shop then play notification
if (shopid == thisShopID)
{
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
$('#loading').show();
// Partial View to Update LatestSales for this Shop
$("#new-Sales").load('#Url.Action("GetLatestSales", "Shop")')
$('#loading').hide();
console.log('New Sale happened, Notification Played');
}
};
// Start the connection.
$.connection.hub.start().done(function () {
console.log('signalR connection started');
}).fail(function (e) {
alert(e);
});
});
</script>
Used Howler.js Plugin to play notification , check this post.
Hope helps someone.

How to connect to SQL Server with windows authentication from Node.JS using mssql module

Hi I'm unable to connect to SQL server that is using windows authentication in node js. I'm using the mssql module. The error message is :
[ConnectionError: Login failed for user ''. The user is not associated with a trusted SQL Server connection.]
name: 'ConnectionError',
message: 'Login failed for user \'\'. The user is not associated with a trusted SQL Server connection.',
code: 'ELOGIN' }
Here is my code:
config = {
server : "localhost\\MSSQLSERVER",
database : "mydatabase",
port : 1433
}
function loadDepts() {
var conn = new sql.Connection(config);
var request = sql.Request(conn);
conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
request.query("select deptid, deptname from departments", function(err, table) {
if (err) {
console.log(err);
return;
}
else {
console.log(table);
}
conn.close();
});
});
}
loadDepts();
Since this is a fairly visible answer, I wanted to add in a code snippet that worked for me with Trusted Connection. Got to it from getglad's edited answer.
const sql = require("mssql");
require("msnodesqlv8");
const conn = new sql.Connection({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
Using trusted connection, I was able to execute stored procedures, log the output, and close the connection without any trouble, and msnodesqlv8 has been updated more recently than any of the other drivers (latest release was October 2016 as of 11/3/2016), so that seems to be a safe choice as well.
And here's an example using mssql#4.0.4. The only changes are the initial require, which pull in msnodesqlv8 from within mssql, and sql.Connection is now sql.ConnectionPool. You will also need to change your stored procedure calls since the response is different, noted here. Credit to Jon's answer since he updated mine before I did!
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
I have been struggling too for some time about how to use mssql + Windows Auth, here is how i got it to work on my project.
As pointed out in the mssql documentation, you need msnodesqlv8 installed too.
npm install msnodesqlv8
Now, following on Aaron Ballard's answer, you use it like this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
database: 'database',
server: 'server',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
As a note, i tried to add this as a comment on Aaron's answer, as mine is just a complement/update to his, but i don't have enough reputation to do so.
I have never been able to get mssql + windows auth to work for any of my projects. Try edge and edge-sql - it has worked for me. Be sure you install all the required packages.
https://github.com/tjanczuk/edge
https://github.com/tjanczuk/edge-sql
From there, it's pretty steamlined.
var edge = require('edge');
var params = {
connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
source: "SELECT TOP 20 * FROM SampleData"
};
var getData = edge.func( 'sql', params);
getData(null, function (error, result) {
if (error) { console.log(error); return; }
if (result) {
console.log(result);
}
else {
console.log("No results");
}
});
EDIT
Well... 10 days after my original answer, apparently mssql added Windows Auth to the package. They heard our cries :) See here. I have not tested it yet, but it is officially in my backlog to test integration. I will report back.
FWTW, if mssql fits your needs, I would go with it, as 1) edge-sql has been dormant for 2 years and 2) the primary contributor has said he has left projects like this "in the caring hands of Microsoft", since he no longer works there.
EDIT 2
This keeps getting upvotes and there are comments saying some of the other answers' code examples either aren't working or aren't working on Windows.
This is my code using mssql, working on Windows, with msnodesqlv8 also installed:
var sql = require('mssql/msnodesqlv8');
var config = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client XX.0};Server={SERVER\\NAME};Database={dbName};Trusted_Connection={yes};',
};
sql.connect(config)
.then(function() {
...profit...
})
.catch(function(err) {
// ... connect error checks
});
I've tried many variations and this is my complete solution.
I'm using SQL server Express.
I'm connecting, in the first instance, to the MASTER database only.
You only NEED to change "YOURINSTANCE\\SQLEXPRESS".
(Be sure to maintain the double-slash above!!!)
I'm using INTEGRATED SECURITY too.
The query relies on nothing at all (in your database).
You need to add your node packages
==> NPM INSTALL MSSQL and
==> NPM INSTALL msnodesqlv8
Hopefully, your connection issues will be a thing of the past.
Maybe.
Please.
// More here -> https://www.npmjs.com/package/mssql
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=YOURINSTANCE\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT 1 AS justAnumber', (err, result) => {
console.log(".:The Good Place:.");
if(err) { // SQL error, but connection OK.
console.log(" Shirtballs: "+ err);
} else { // All is rosey in your garden.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection borked.
console.log(".:The Bad Place:.");
console.log(" Fork: "+ err);
});
For me
I used connection setting as below
"server":"",
"domain":"", //sepcify domain of your user
"port": ,
"user":"", // enter username without domain
"password":"",
"database":""
and the TS code
import * as sql from 'mssql';
const pool = await new sql.ConnectionPool(connection).connect();
const result = await pool.request()
.query(`SELECT count(idpart) part_computed FROM demo.PARTs;`);
pool.close();
return Promise.resolve(result.recordset);
I could only get a Trusted Connection working using msnodesqlv8 (limited to Windows environments) with a connection string (rather than a config object).
const sql = require("msnodesqlv8");
const connectionString = function(databaseName) {
return "Server=.;Database=" + databaseName + ";Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
}
sql.query(connectionString("DatabaseName"), "SELECT * FROM dbo.Table1" , (err, recordset) => {
if(err) {
// Do something with the err object.
return;
}
// else
// Do something with the recordset object.
return;
});
Below code is working for me......
const sql = require('mssql/msnodesqlv8')
// config for your database
var config = {
driver: 'msnodesqlv8',
server: 'serverNAme\\SQLEXPRESS',
database: 'Learn' ,
options: {
trustedConnection: true
}
};
It worked for me
need to install msnodesqlv8 and mssql. also .......:)
var dbConfig = {
driver: 'msnodesqlv8',
server: "DESKTOP-66LO4I3",
database: "FutureHealthCareWeb",
user: "sa",
password: "pass#123",
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
var sql = require('mssql/msnodesqlv8');
sql.connect(dbConfig, function (err) {
if (err) { console.log(JSON.stringify(err)+'..............') }
else {
console.log('Connected')
}
}
);
this worked for me
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "DB name",
server: "server name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then((err) => {
if(err) throw err;
else console.log("connected");
const req = new sql.Request(conn)
req.query("select * from table", function(error, res){
console.log(res)
})
});
I struggled to connect with mssql server which run in remote windows server using windows authentication mode . Then i found the solution just used like below code.
sql.connect("Data Source=172.25.x.x,1433;User Id=CSLx\\Name;Password=xxxxxx1234;Initial Catalog=giveTHedataabseNamel;Integrated Security=True",function(err){ }
I've just add domain: "DNAME", in config, and as result this config helps me connect to MS SQL with windows auth.
const config = {
driver: 'msnodesqlv8',
domain: "DNAME",
user: 'username',
password: 'pass',
server: '7.6.225.22',
database: 'DBNAME',
requestTimeout: 3600000, //an hour
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
This version doesn't need a username or password.
To use windows authentication I installed mssql and msnodesqlv8.
Then in my app.js file:
const mssql = require('mssql/msnodesqlv8');
Note it is mssql not sql if you're using this example.
var config = {
database:'YOUR DATABASE NAME',
server: 'localhost\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
enableArithAbort: true
}
};
You need to change the database name in config. Other than that it should work. My example:
app.get('/', function (req, res) {
mssql.connect(config, function (err) {
if (err) console.log(err);
var request = new mssql.Request();
request.query('select * from dbo.visit', function (err, result) {
if(err) console.log(err);
console.log(result);
});
});
});

Connect to SQL Server database from Node.js

The question duplicates some older questions, but the things may have changed since then.
Is there some official support for connecting to SQL Server from Node.js (e.g. official library from MS)? Or at least some well-maintained third-party library appropriate for a production-grade application?
We usually use ASP.NET MVC/SQL Server combination, but currently I have a task for which express/Node.js seems to be more appropriate (and I'd like to play with something new), so the question is whether we can rely on a Node.js and SQL Server interaction.
UPD: It seems that Microsoft has, at last, released the official driver: https://github.com/WindowsAzure/node-sqlserver
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");
var dbConfig = {
server: "localhost\\SQL2K14",
database: "SampleDb",
user: "sa",
password: "sql2014",
port: 1433
};
function getEmp() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM emp").then(function (recordset) {
console.log(recordset);
conn.close();
})
.catch(function (err) {
console.log(err);
conn.close();
});
})
.catch(function (err) {
console.log(err);
});
//--> another way
//var req = new sql.Request(conn);
//conn.connect(function (err) {
// if (err) {
// console.log(err);
// return;
// }
// req.query("SELECT * FROM emp", function (err, recordset) {
// if (err) {
// console.log(err);
// }
// else {
// console.log(recordset);
// }
// conn.close();
// });
//});
}
getEmp();
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE:
There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
We just released preview driver for Node.JS for SQL Server connectivity. You can find it here:
Introducing the Microsoft Driver for Node.JS for SQL Server.
The driver supports callbacks (here, we're connecting to a local SQL Server instance):
// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
for (var i = 0; i < results.rows.length; i++) {
console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
}
});
});
Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):
// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";
var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });
If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues
There is a module on npm called mssqlhelper
You can install it to your project by npm i mssqlhelper
Example of connecting and performing a query:
var db = require('./index');
db.config({
host: '192.168.1.100'
,port: 1433
,userName: 'sa'
,password: '123'
,database:'testdb'
});
db.query(
'select #Param1 Param1,#Param2 Param2'
,{
Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
,Param2: { type : 'Int',value : 321 }
}
,function(res){
if(res.err)throw new Error('database error:'+res.err.msg);
var rows = res.tables[0].rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
}
}
);
You can read more about it here: https://github.com/play175/mssqlhelper
:o)
msnodesql is working out great for me. Here is a sample:
var mssql = require('msnodesql'),
express = require('express'),
app = express(),
nconf = require('nconf')
nconf.env()
.file({ file: 'config.json' });
var conn = nconf.get("SQL_CONN");
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";
app.get('/api/brands', function(req, res){
var data = [];
var jsonObject = {};
mssql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("dbo.storedproc", function (err, results) {
if(err) {
console.log(err);
res.send(500, "Cannot retrieve records.");
}
else {
//res.json(results);
for (var i = 0; i < results.rows.length; i++) {
var jsonObject = new Object()
for (var j = 0; j < results.meta.length; j++) {
paramName = results.meta[j].name;
paramValue = results.rows[i][j];
jsonObject[paramName] = paramValue;
}
data.push(jsonObject); //This is a js object we are jsonizing not real json until res.send
}
res.send(data);
}
});
});
});
//start the program
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'datapullman',
password: 'system',
server: 'localhost',
database: 'chat6'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * From emp", function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//create a table as emp in a database (i have created as chat6)
// programs ends here
//save it as app.js and run as node app.js
//open in you browser as localhost:5000

Resources