How Do i connect sails to mongodb? - javascript

Im new to sails Js and mongodb. I am absolutely a newbie.
Problem:
I already have a user collection on my mongodb database. I want to connect it to sails to display the list of collection.
Ive seen sails js documentations. I already installed sails-mongo adapter and edited the connection.js....
module.exports = {
// this is my model
attributes: {
firstname: {
type: 'string'
}
},
findUser: function(opts,callback){
///// How am I going to connect to mongo and query the users ?
//// user.find('John Doe') wont work here.
}
}

Run: npm install sails-mongo
in config/connections.js uncomment section related to mongo and enter necessary info there
someMongodbServer: {
adapter: 'sails-mongo',
host: 'mongohost.com',
port: 55915,
user: 'user',
password: 'password',
database: 'dbname'
},
in config/models.js enter you connection adapter variable
...
connection: 'someMongodbServer',
...
done
EDIT:
In order to get the data from database use the following:
User.find({firstname: 'John Doe'}).exec(function(error, user) {
console.log(user);
});

Related

SQL Server connection using tedius and sequelize in NodeJs

Getting below error when trying to connect SQL Server Local database in NodeJs Sequelize.
name: 'SequelizeHostNotFoundError',
message: 'Failed to connect to abcdd\SQL2K12:1433 - getaddrinfo ENOTFOUND abcdd\SQL2K12',
code: 'ESOCKET
Below are my configuration settings and the credentials are correct
"use_env_variable": false,
"username": "username",
"password": "password#123",
"database": "db_test",
"host": "abcdd\\SQL2K12", //actual db hotsname is abcdd\SQL2K12
"dialect": "mssql",
"operatorsAliases": false,
"dialectOptions": {
"encrypt": true,
"trustedConnection": true
}
In SSMS its working fine. And is there issue with port number? As I am not using a port in SSMS.
For me works adding instanceName instead of putting server: 'SERVER\SQLSERVER2K06',
just put "SERVER".
var config = {
server: 'SERVER',
authentication: {
type: 'default',
options: {
userName: 'user',
password: '*****'
}
},
options: {
database: 'NAME',
instanceName: 'SQLSERVER2K06' /*It Works! */
}
}
for tedious:
options.instanceName
The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable.
(no default)
Mutually exclusive with options.port.
check the comments:
https://github.com/tediousjs/node-mssql/issues/130
var config = {
userName: 'test01',
password: 'test01',
server: 'localhost',
options: {
"database":"TestDB",
"instanceName": "SQL2012"
}
};
in your case
var config = { server: 'abcdd', options: {"instanceName": "SQL2K12" } };
Also, make sure TCP enabled on your SQL Server: Sql Server Configuration Manager > SQL Server Network Configuration > Protocols for SQLSERVER > TCP/IP

How to update clients when database is edited outside of feathersjs app

I have two server-side applications editing the same database.
One server is a feathersjs app and another is a simple nodejs app. A frontend app connects to the feathersjs app via feathersjs client.
How, when the nodejs app edits the database, can I update clients connected to the feathersjs app? As currently any changes made outside the featherjs app aren't reflected on the feathersjs clients.
Can I trigger the patched event somehow and force the clients to pull down the updated data?
if you are using mongodb with WiredTiger storageEngine you can use the collection.watch() function and add a monitor in your feathers app something like this
//src/services/monitor.js
module.exports = function(app){
//get mongo client
const mongoClient = app.get('mongoClient');
//connect db
mongoClient.then(db => {
//collection to watch
const collection = db.collection('your_collection_name')
//watch collection
const changeStream = collection.watch({ fullDocument: 'updateLookup' });
//on some data changed
changeStream.on('change', data => {
console.log ( 'something is changed in your collection' , data )
//your service.emit
});
})
}
Then I added this simple monitor in the /src/services/index.js (maybe not the right way but it works)
//src/services/index.js
...
const monitor = require('./monitor.js');
module.exports = function (app) {
...
app.configure(monitor);
...
};
Data returned on every change on the collection
{ _id:
{ _data:
'825C7F03230000001C29295A100490DEF2C65812410FABF0DE46F9C89D7246645F696400645C1AC097B189CBD5D4A24D330004' },
operationType: 'replace',
clusterTime:
Timestamp { _bsontype: 'Timestamp', low_: 28, high_: 1551827747 },
fullDocument:
{ _id: 5c1ac097b189cbd5d4a24d33,
id: '12',
language: 'it-IT',
category: 'some data',
slug: '',
description: 'some data',
src:'',
color: 'card',
status: true,
home: true,
order_int: '3',
visual: 'card' },
ns: { db: 'mydb', coll: 'mycollection' },
documentKey: { _id: 5c1ac097b189cbd5d4a24d33 } }
More info here https://docs.mongodb.com/manual/reference/method/db.collection.watch/
As you pointed out, only changes made through the Feathers API will be reflected but on the server you can always emit the event you need via service.emit:
dbConnection.on('someDatabaseUpdate', data => {
app.service('messages').emit('patched', data);
app.service('messages').emit('updated', data);
});
Things to note here (also discussed in this issue):
There will be no user or any other information about the method call
data will not be run through any service hooks

Configure Mandrill with Meteor fail

I always get error saying:
TypeError: Cannot call method 'config' of undefined.
This is my startup function on server.js. What do I do wrong?
Meteor.startup(function() {
return Meteor.Mandrill.config({
username: "SMTP Username",
key: "Valid API Key",
password: "Valid API Key",
port: "587",
host:"smtp.mandrillapp.com"
});
});
The meteor startup function is not designed to return something, this is your first error.
On an other hand, I can see on their documentation that you have to configure the object Mandrill directly.
if (Meteor.isServer) {
// server code
Mandrill.config({
username: "SMTP Username",
key: "Valid API Key",
password: "Valid API Key",
port: "587",
host:"smtp.mandrillapp.com"
// baseUrl: 'https://mandrillapp.com/api/1.0/' // update this in case Mandrill changes its API endpoint URL or version
});
// you can put a Meteor startup here if you want :
Meteor.startup(function() {
// Do somthing else, like populating, ...
});
}

Sails js: How can I define two MySQL connections to two different databases in a single model in Sails js?

I have created a model Employee.js and EmployeeController.js. I have defined two connections in Employee.js file:
module.exports = {
connection: 'LocalhostMysqlServer',
attributes: {
name:{
type:"string",
required:true,
},
empnum:{
type:"integer",
required:true,
unique: true
},
email:{
type:"string",
required:true,
unique: true
}
},
connection: 'LocalhostMysqlServer1',
attributes: {
username:{
type:"string",
required:true,
},
usrnum:{
type:"integer",
required:true,
unique: true
},
email:{
type:"string",
required:true,
unique: true
}
},
};
Below is my EmployeeController.js file where I have included two views: CreateEmp & CreateUsr, associated with this Model and controller. Also, I have defined two functions to handle the post requests from these views. Here, I want to insert the data from CreateEmp to a different database and from CreateUsr to a different database.
module.exports = {
createEmp: function(req,res){
'use strict';
res.view('new.ejs');
},
createUsr: function(req,res){
'use strict';
res.view('newUser.ejs');
},
createEmployee: function(req, res){
if(req.method=="POST"){
var name= req.param("name");
var empnum= req.param("empnum");
var email= req.param("email");
var insert= "INSERT INTO employee(name, empnum, email) VALUES ('"+name+"', "+empnum+", '"+email+"')";
Employee.query(insert, function(err, record){
if(err)
console.log(err);
else{
console.log(record);
}
})
}
},
createUser: function(req, res){
if(req.method=="POST"){
var username= req.param("username");
var usrnum= req.param("usrnum");
var email= req.param("email");
var insert= "INSERT INTO user (username, usrnum, email) VALUES ('"+username+"', "+usrnum+", '"+email+"')";
Employee.query(insert, function(err, record){
if(err)
console.log(err);
else{
console.log(record);
}
})
}
},
};
I have included my config/connections.js here:
module.exports.connections = {
localDiskDb: {
adapter: 'sails-disk'
},
LocalhostMysqlServer: {
adapter: 'sails-mysql',
//module: 'sails-mysql',
host: 'localhost',
user: 'root',
password: 'disisanshu',
database: 'sailsTest1',
tableName: 'employee'
},
LocalhostMysqlServer1: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root',
password: 'disisanshu',
database: 'sailsTest2',
tableName: 'user'
}
};
Here I have included my model.js below:
module.exports.models = {
// migrate: 'alter'
connection: 'LocalhostMysqlServer',
migrate: 'alter',
connection1: 'LocalhostMysqlServer1',
migrate: 'alter'
};
There is no reason why you should do such a thing.
You are probably looking to reduce your load on your database. A master-slave database kind of structure should be implemented instead.
Also, the database should be totally de-coupled from the rest of your app.That is why you should have only one connection.
If the load on your database increases, scale it horizontally (add more servers to distribute the load)- mySQL is good for these things. This can and should be done without any change in your app code.
You can't use two different connections in the same model--hopefully there's no documentation that says this is possible! You'll just have to define two different models.
Also, it's not really valid Javascript to declare the same key twice in an object (as you do with connection in your first code block, and with migrate in your last). The second definition will just override the first if they're different.

Accessing MySQL database in node.js - internal assertion fails

I'm trying to connect to MySQL database from node.js using db-mysql library. Everything works great with example code, but now I'm trying to write a simple ORM.
This is my code:
require.paths.unshift('/usr/lib/node_modules'); // default require.paths doesn't include this
function Model() {
this.database = null;
}
Model.prototype.getDB = function(callback) {
if (this.database != null)
callback(this.database);
else {
console.log("Connecting to database...");
this.database = require("db-mysql").Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
});
}
}
exports.Model = Model;
And simple code I use for testing:
orm = require('./orm');
model = new orm.Model();
model.getDB(function (db) { console.log("callback'd"); });
It looks fine (at least for me), however node.js fails with internal assertion:
Connecting to database...
node: /usr/include/node/node_object_wrap.h:61: void node::ObjectWrap::Wrap(v8::Handle<v8::Object>): Assertion `handle->InternalFieldCount() > 0' failed.
Przerwane (core dumped)
After further investigation, if fails before/during creating Database object. I have no idea why this happens. I first though that it's because I was using git node.js version, but it fails with current release (v0.4.7) as well.
I'm trying to track down this issue in node.js code, with no success at the moment.
Oh, it was me to fail hard. It seems that having Python background is undesired in JavaScript world ;).
Database initialization should look like:
db = require("db-mysql");
new db.Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
}).connect();
So, I basically forgot to call new and connect().

Categories

Resources