I use node.js to communicate with the mongodb-server. The send of the variables and the export of the function are working. The writing in the DB isnt and I can't find the error. It seems to be a problem with the insert, but i cant find it.....
mongo.js
exports.InsertDocument = function InsertDocument(tblname, OutUser, OutEmail, OutDate) {
console.log("function InsertDocument called");
console.log(tblname + OutUser + OutEmail + OutDate);
var document = {tablename:tblname, out_user:OutUser, out_email:OutEmail, out_date:OutDate };
db.collection('movements').insert(document, function(err, results) {
if (err) throw err;
console.log("data saved");
db.close();
});
}
index.js
/* POST home page. */
router.post('/create_movement', function(req, res) {
var tblname = req.body.tablename,
OutUser = req.body.out_user,
OutEmail = req.body.out_email,
OutDate = req.body.out_date;
mongo.InsertDocument(tblname, OutUser, OutEmail, OutDate);
res.send("succesfull");
});
node.js console
Example app listening at http://:::3005
Connection established to mongodb://localhost:27017/straff
function InsertDocument called
test234
POST /create_movement 500 317.042 ms - 954
out of rest client
<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>db is not defined</h1><h2></h2><pre>ReferenceError: db is not defined
at Object.InsertDocument (D:\test1\mongo.js:26:2)
at D:\test1\routes\index.js:17:9
at Layer.handle [as handle_request] (D:\test1\node_modules\express\lib\router\layer.js:82:5)
at next (D:\test1\node_modules\express\lib\router\route.js:110:13)
at Route.dispatch (D:\test1\node_modules\express\lib\router\route.js:91:3)
at Layer.handle [as handle_request] (D:\test1\node_modules\express\lib\router\layer.js:82:5)
at D:\test1\node_modules\express\lib\router\index.js:267:22
at Function.proto.process_params (D:\test1\node_modules\express\lib\router\index.js:321:12)
at next (D:\test1\node_modules\express\lib\router\index.js:261:10)
at Function.proto.handle (D:\test1\node_modules\express\lib\router\index.js:166:3)</pre></body></html>
The error tells you everything:
ReferenceError: db is not defined
at Object.InsertDocument (D:\test1\mongo.js:26:2)
You have to connect to your database, and add all the details into a variable called db.
Using Mongojs would be like:
var mongojs = require('mongojs');
var db = mongojs(connectionString, [collections]);
You'll have to check the docs for the driver your using.
Related
js and using tedious to connect. Connection is successful and I'm able to connect. However in period of time I would lose connect and receive these errors in Azure.
RequestError: Requests can only be made in the LoggedIn state, not the Final stateat RequestError (D:\home\site\wwwroot\node_modules\tedious\lib\errors.js:32:12)
at Connection.makeRequest (D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:2380:49)at Connection.execSql (D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:2034:10)at submitCode (D:\home\site\wwwroot\controller\mssqlController.js:121:16)at Layer.handle [as handle_request] (D:\home\site\wwwroot\node_modules\express\lib\router\layer.js:95:5)at next (D:\home\site\wwwroot\node_modules\express\lib\router\route.js:137:13)at Route.dispatch (D:\home\site\wwwroot\node_modules\express\lib\router\route.js:112:3)at Layer.handle [as handle_request] (D:\home\site\wwwroot\node_modules\express\lib\router\layer.js:95:5)at D:\home\site\wwwroot\node_modules\express\lib\router\index.js:281:22at Function.process_params (D:\home\site\wwwroot\node_modules\express\lib\router\index.js:335:12) {code: 'EINVALIDSTATE'}[0mPOST /login [32m200 [0m11.820 ms - 27[0m
Here is my code:
let config = {
server: '',
authentication: {
type: 'default',
options: {
userName: '',
password: ''
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: ''
}
};
let connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("err", err);
});
let Request = require('tedious').Request
let TYPES = require('tedious').TYPES;
My question is where and what can I add to reconnect or reset SQL Server in Azure if connection is lost?
You can try using the below code to retry the connection:
let intervalFunction;
const INTERVAL_DURATION = 4000;
if (require.main === module){
console.log("Listening on http://localhost:" + config.port + " ...");
app.listen(config.port);
// try to connect to db and fire main on succes.
intervalFunction = setInterval(()=> getConnection(), INTERVAL_DURATION);
}
function getConnection() {
sql.close();
sql.connect(config.database).then(() => {
sql.close();
clearInterval(intervalFunction);
main();
}).catch(function(err) {
console.error(err);
console.log(`DB connection will be tried again in ${INTERVAL_DURATION}ms`)
sql.close();
});
}
Once the initial connection has been made but it got lost in the meantime, then the pool will pick up the connection automatically and handle your connections.
I suggest using the mssql node package, which still uses tedious, and using a pool -- which will auto-reconnect.
https://www.npmjs.com/package/mssql#connections-1
Otherwise, you can look for connection.on('end') event, or error event, and write a custom function to retry the connection then. See an example of listening here: https://github.com/tediousjs/tedious/blob/master/examples/simple-client.js
I'm creating a simple web API using NodeJS express, for some home domotics. For my TV I'm using the following library --> https://github.com/hobbyquaker/lgtv2.
When I run my code locally, for example;
var lgtv = require('lgtv2')({
url: 'ws://192.168.178.31:3000'
});
lgtv.on('error', function(err) {
console.log(err);
});
lgtv.on('connect', function() {
console.log('connected');
lgtv.request('ssap://system/turnOff', function(err, res) {
lgtv.disconnect();
});
});
It run's fine. However, the same code, deployed to my Synology NAS, results in an error.
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at exports.join (path.js:358:36)
at module.exports (/volume1/web/NodeJS/node_modules/persist-path/index.js:19:22)
at new LGTV (/volume1/web/NodeJS/node_modules/lgtv2/index.js:47:16)
at LGTV (/volume1/web/NodeJS/node_modules/lgtv2/index.js:38:16)
at Object.module.exports.setNetflix (/volume1/web/NodeJS/controllers/tv.js:50:36)
at /volume1/web/NodeJS/routes/routes.js:43:12
at Layer.handle [as handle_request] (/volume1/web/NodeJS/node_modules/express/lib/router/layer.js:95:5)
at next (/volume1/web/NodeJS/node_modules/express/lib/router/route.js:137:13)
The only actual difference I can spot is the NPM version, which is v10.14.1 locally and v0.10.48 on my NAS. Is there any way to bypass this problem and get this working?
Randy
It is very strange library.
Try this code
console.log('Platform = ',process.platform);
var lgtv = require('lgtv2')({
url: 'ws://192.168.178.31:3000',
clientKey: ''
});
lgtv.on('error', function(err) {
console.log(err);
});
lgtv.on('connect', function() {
console.log('connected');
lgtv.request('ssap://system/turnOff', function(err, res) {
lgtv.disconnect();
});
});
I'm using NodeJS with express, consign, body-parser, etc.
I'm trying to load a module in a var, so i can use their functions, but i'm getting a:
TypeError: Cannot read property 'listar' of undefined
at app.get (/home/sartori/Documentos/Projetos/react-system/api/controllers/autores.js:6:11)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:335:12)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:275:10)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express-validator/lib/express_validator.js:250:5
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
Here's my controller:
module.exports = app => {
app.get('/api/autores', (req,res) => {
let connection = app.connection.connectionFactory();
let autores = app.models.AutoresDao(connection);
autores.listar((error,result) => {
if(error) {
console.log('Erro ao listar os autores: ' + error);
res.status(500).send(error);
} else {
res.json(result);
}
});
});
}
Here's the AutoresDao:
function AutoresDao(connection) {
this._connection = connection;
}
AutoresDao.prototype.listar = callback => this._connection.query('SELECT * FROM autores', callback);
module.exports = function() {
return AutoresDao;
}
The problem is: Cannot read property 'listar' of undefined.
Apparently the problem is loading the AutoresDao file.
I'm 100% sure of files path, AutoresDao is inside models folder, already loaded on consign. The same for the controller, connection, express config etc.
Any idea of what i'm doing wrong?
You need to be using the 'new' keyword if you are going to format your object constructor function in that manner. You will have to reformat your AutoresDao function to explicitly return an object, or use the 'new' keyword when you assign it to autores in the controller.
Please checkout this article for an explanation of the different instantiation patterns.
https://medium.com/dailyjs/instantiation-patterns-in-javascript-8fdcf69e8f9b
Hope that helps! Cheers.
var categoryList = new Referral({categoryList : category});
categoryList.pre('save', function (next) {
Referral.find({categoryList : category}, function (err, docs) {
if (!docs.length){
next();
}else{
console.log('Data exists: ', category);
next(new Error("Data exists!"));
}
})
})
Referral is my variable assigned to my schema.
categoryList is the object
This gives an error
TypeError: categoryList.pre is not a function at
D:\Aventyn\ClipCare_v2\app\api.js:112:18 at Layer.handle [as
handle_request]
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5)
at next
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request]
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5)
at
D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:277:22
at Function.process_params
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:330:12)
at next
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:271:10)
at Function.handle
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:176:3)
at router
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:46:12)
at Layer.handle [as handle_request]
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:312:13)
at
D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:280:7
at Function.process_params
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:330:12)
at next
(D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:271:10)
at
D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:618:15
Try changing:
categoryList.pre('save', function (next) {
// ...
})
to:
categoryList.schema.pre('save', function (next) {
// ...
})
The .pre() is a method of the Mongoose schema, not a model.
Middleware (like pre hooks) are part of a schema. It looks like you're trying to use it on a single document, which is not how it works.
Instead, use it on the schema that you used to create the Referral model:
ReferralSchema.pre('save', ...);
This does mean that the pre hook will be applied to all documents of that schema.
I'm starting with Parse and Node.js. I'm trying to retrieve data from Parse db and I don't manage to.
var Parse = require('parse').Parse;
Parse.initialize("*************", "*****************");
module.exports = {
index: function(req, res, next){
var query = new Parse.Query(Parse.Event);
query.find({
success: function(results) {
console.log(results);
},
error: function(error) {
console.log(error.message);
}
});
}
}
And I got this error :
TypeError: Cannot read property 'prototype' of undefined
at Object.Parse.Query (/Users/tchiss_a/test/webapp/node_modules/parse/build/parse-latest.js:7771:33)
at module.exports.index (/Users/tchiss_a/test/webapp/api/Events.js:7:20)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:235:24
at Function.proto.process_params (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:313:12)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:296:3)
Can someone help me please ?
There is a fix listed in the comments, but the actual problem here is that you're treating a user-defined class "Event" like a Parse class.
change
var query = new Parse.Query(Parse.Event);
to
var query = new Parse.Query("Event");