As the title says, I'm running into a syntax error using node-postgres. Here's what the code looks like
const {Pool, Client} = require('pg')
const pool = new Pool({
user: '<user>',
host: '<host>',
database: '<database>',
password: '<pw>',
port: <port>
})
let query = `SELECT * FROM user JOIN notifications ON user.user_id = notifications.user_id WHERE user_id=$1`
let values = ["123"]
pool.query(query, values)
.then(() => { /* do something */} )
.catch((err) => { console.log(err)} )
Based on this query, I get a syntax error with the message
syntax error at or near "."
Since the same query runs fine in pgAdmin, my guess is that it's module specific, but I haven't figured out what the problem is.
Any help much appreciated!
Edit: added missing bracket, thanks to Sreeragh A R
user is reserved word in postgresql you have to escape user using double quotes
let query = `SELECT * FROM "user" JOIN notifications ON "user".user_id = notifications.user_id WHERE "user".user_id=$1`
Related
I am trying to use IN parameter in the WHERE clause of select query in IBM_DB2 of nodeJS.
I tried the following:
const conn = await ibmdb.open(connStr);
const query = 'SELECT NAMES FROM DB.TABLE WHERE SETUP_DATE > ? AND ID IN (?)';
const prepareSmt = await connection.prepare(query);
const result = await prepareSmt.execute(['230101', ['123','124','125']]);
const data = await result.fetchAllSync();
console.log("result = ", data);
when the above gets executed: I always get error:
Error: Wrong param format!
at /Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/odbc.js:1550:12
at SimpleQueue.next (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:34:5)
at SimpleQueue.maybeNext (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:22:10)
at SimpleQueue.push (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:15:8)
at ODBCStatement.odbc.ODBCStatement.execute (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/odbc.js:1524:14)
at main (/Users/USERNAME/workspace/learning/ibmDB2/index.js:14:29)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
The same query works when i use without IN parameter. Can someone please help me how to frame the query and pass the values when IN parameter used in the select query.
Using TOAD we are able to execute a query like this:
Select NAMES from DB.TABLE where SETUP_DATE > '230101' AND ID IN ('123','124','125')
And i am trying to execute the same from IBM_DB2 nodejs.
Thanks,
Naveen
I am currently using sql.js to view my database:
async function sqliteRun () { // eslint-disable-line
const SQL = await initSqlJs({
locateFile: () => 'misc/sql-wasm.wasm'
})
const db = new SQL.Database('public/misc/test.sqlite')
const stmt = db.prepare('SELECT * FROM test')
while (stmt.step()) { //
const row = stmt.getAsObject()
console.log('Here is a row: ' + JSON.stringify(row))
}
}
But then I am getting an error: "File is not a database". I double checked my file and it seems correct (I was able to view it in a sqlite file browser)
I also tried using .db and .sql, all give out the same error.
I prefer to load the file directly in the new SQL.Database() constructor. I wont be able to use fs. Any thoughts on how to do this?
Currently the only thing I have in my file is the following:
var mongo = require('mongodb').MongoClient,
url = 'mongodb://localhost:27017/learnyoumongo';
console.log(mongo);
When I run the verify command, I get the following error:
/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37
db.collection('parrots').remove({}, function(err) {
^
TypeError: Cannot read property 'collection' of undefined
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37:5)
at next (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:260:17)
at Exercise.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:266:5)
at Workshopper.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:191:12)
at Workshopper.done (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:323:19)
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:149:14)
at /usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:136:16
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/filecheck.js:10:14)
at FSReqWrap.oncomplete (fs.js:95:15)
When I took a look at the exercises.js file, I see the error is pointing to the .addCleanup function and the db it is trying to close is undefined.
This seems like a connection/configuration error, but I passed the first two modules. Can anyone help?
Update
This is definitely a connection error. The previous scenario was created using the command in the workshop module mongod --port 27017 --dbpath=./data, however when I opened a new terminal tab and just ran mongo without any arguments, the verify command actually output the "Actual/Expected" evaluation and module results.
To the user who asked for the rest of the script, please understand if you are unfamiliar with nodeschool that this is an entire repository with module based automated/interactive tutorials, so this is not all of the code. In any case, here is what you requested:
var mongo = require('mongodb').MongoClient
, exercise = require('workshopper-exercise')()
, filecheck = require('workshopper-exercise/filecheck')
, execute = require('workshopper-exercise/execute')
, comparestdout = require('workshopper-exercise/comparestdout')
exercise = filecheck(exercise)
exercise = execute(exercise)
exercise = comparestdout(exercise)
var db, url = 'mongodb://localhost:27017/learnyoumongo'
exercise.addSetup(function(mode, cb) {
var self = this
this.submissionArgs = [3]
this.solutionArgs = [3]
mongo.connect(url, function(err, _db) {
if (err) return cb(err)
db = _db
col = db.collection('parrots')
col.insert([{
name: 'Fred'
, age: 1
}, {
name: 'Jane'
, age: 3
}, {
name: 'Jenny'
, age: 10
}], cb)
})
})
exercise.addCleanup(function(mode, pass, cb) {
db.collection('parrots').remove({}, function(err) {
if (err) return cb(err)
db.close()
cb()
})
})
module.exports = exercise
I think that should be:
var mongo = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/learnyoumongo', function(err, db) {
console.log(err);
});
There was definitely a connection problem. I'm not sure exactly where the bug was, but I reloaded learnyoumongo and reinstalled a couple of node packages. When I did that I had to go back and change permissions on the data directory again.
My recommendation if anyone else faces strange config errors, is to try to reinstall. Then when you connect, it doesn't hurt to re-verify the CONNECT module to make sure you have a good connection when you start your work space.
Am using mongoose - 3.8.8 to connect to Mongo DB. I tried out initializeOrderedBulkOp() - a new feature of MongoDB - 2.6 in mongo Shell and i got proper output. But am not able to do the same with mongoose.
Here is a sample code
var mongoose = require('mongoose');
var conn = mongoose.createConnection('mongodb://localhost:27017/testDB');
conn.on('error', function callback (err,data) {
console.log('Error in connecting to DB');
});
var Schema = mongoose.Schema,
schema = new Schema({id:Number},{strict:false}),
modelObj = conn.model('', schema, 'documents');
var query = modelObj.initializeOrderedBulkOp();
Am getting error like
"modelObj has no method 'initializeOrderedBulkOp"
Any suggestions on this ???
You're really close. You need to drop down a level to the native driver. You can do that like so:
var query = modelObj.collection.initializeOrderedBulkOp();
From there you can do things like:
// queue a doc to be inserted
query.insert({ name: 'Some Name' })
// ... more inserts ...
// execute the bulk operation
query.execute(next)
One thing to note though, the un-ordered equivalent, initializeUnOrderedBulkOp(), does not seem to exist in version 3.8.9.
This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.
Code sample:
var db1 = require('mongoose');
db1.connect('my.db.ip.address', 'my-db');
var db2 = require('mongoose');
db2.connect('my.db.ip.address', 'my-db');
db2.connection.close();
db1.connection.close();
Any idea how to make it work?
connect() opens the default connection to the db. Since you want two different connections, use createConnection().
API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection
To add on Raghuveer answer :
I would also mention that instead of using mongoose directly (you are probably using it this way you end up on this post) :
require('mongoose').model(...);
You would use the returned connection :
var db = require('mongoose').connect('xxx', 'yyy');
db.model(...);
I get this issue while running my tests.
This is what I did to solve it.
//- in my app.js file.
try {
mongoose.connect('mongodb://localhost/userApi2'); //- starting a db connection
}catch(err) {
mongoose.createConnection('mongodb://localhost/userApi2'); //- starting another db connection
}
I had this problem doing unit test with mocha.
The problem came when I added a second test because beforeEach is called twice.
I've solved this with this code:
const mongoose = require('mongoose');
describe('Your test suite', () => {
beforeEach( () => {
if (mongoose.connection.db) {
return; // or done();
} else {
// connect to mongodb
});
describe('GET /some-path', () => {
it('It should...', () => {
});
});
describe('POST /some-path', () => {
it('It should...', () => {
});
});
});
Hope it helps you!
You are attempting to open the default connection ( which is not yet closed ) a 2nd time.
do the following instead
var db = require('mongoose'); //note only one 'require' needed.
var connectionToDb1 = db.createConnection('my.db1.ip.address', 'my-db1');
var connectionToDb2 = db.createConnection('my.db2.ip.address', 'my-db2');
Using mongoose.disconnect(fn):
mongoose.disconnect(() => {
// here it would be possible "reset" models to fix
// OverwriteModelError errors
mongoose.models = {};
// here comes your logic like registering Hapi plugins
server.register(somePlugin, callback);
});
I found this question typing the error message and despite my problem is a bit different I believe it could be useful for those using Hapi. More specifically Hapi + rest-hapi + mocha.
When running mocha with --watch option I was facing both: OverwriteModelError and Error: Trying to open unclosed connection errors.
Simple Solution -
Use mongoose.createConnection() instead of mongoose.connect()
Its occurs because of version issue