Cannot read property 'omitFormat' of undefined - sails.js

I created a table in clickhouse like below :
let clickhouse = new ClickHouse (sails.config.clickhouse);
let query = `CREATE TABLE table1(category String,subcategory String,title String,id Int64) Engine=Log`
and I tried to run the query above as so:
return new Promise((resolve, reject) => {
clickhouse.query (query, function (err, result) {
if (err) {
console.log(err);
}
resolve('success');
});
});
let test = await createTable();
But then I got this error:
Cannot read property 'omitFormat' of undefined
Any solution to this error? Thanks
P.S: I've tried to run the query in Clickhouse client and it works.

You pass not initialized sails.config.clickhouse-param.
Passing the undefined options to ClickHouse-constructor leads to the error in this line.
Look at the console to see the related warning:
> You must provide at least host name to query ClickHouse // <---- !!!
>
> Error: TypeError: Cannot read property 'omitFormat' of undefined
> at ClickHouse.query (/home/runner/node_modules/#apla/clickhouse/src/clickhouse.js:257:60)
> at Promise (evalmachine.<anonymous>:8:26)
> at new Promise (<anonymous>)
> at createTable (evalmachine.<anonymous>:7:10)
> at evalmachine.<anonymous>:17:1
> at Script.runInContext (vm.js:133:20)
> at Object.runInContext (vm.js:311:6)
> at evaluate (/run_dir/repl.js:133:14)
> at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
> at ReadStream.emit (events.js:198:13)
The code reproducing this error (see https://repl.it/repls/FakePortlyExponent):
const ClickHouse = require('#apla/clickhouse')
let clickhouse = new ClickHouse (/*sails.config.clickhouse*/null); // <----- !!!
let query = `CREATE TABLE table1(category String,subcategory String,title String,id Int64) Engine=Log`;
async function createTable() {
return new Promise((resolve, reject) => {
clickhouse.query (query, function (err, result) {
if (err) {
console.log(err);
}
resolve('success');
});
});
}
createTable()
.then(() => {
console.info('Success.');
})
.catch(err => {
console.error('Error:', err);
});

Related

Cannot read collection from MongoDB

So, I'm trying to connect a mongo database and it's already connected. But my issue is that I can't read collection from mongo in another file, it says: db.collection is not a function.
So this is my db.js file:
const { MongoClient } = require('mongodb');
let connection_string = 'mongodb+srv://username:password#cluster0.3ctoa.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
let client = new MongoClient(connection_string, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let db = null
export default () => {
return new Promise((resolve, reject) =>{
if (db && client.isConnected()){
resolve(db)
}
client.connect(err => {
if(err){
reject("Error in connection " + err)
}
else{
console.log("Success")
db = client.db("posts")
resolve(db)
coll = db.collection('posts');
}
});
})
};
The thing is I got successfully connected to a database, but when I try to work with collections it says they are not functions.
This is my second file where I already imported connect from db.js, so here is what I want to do:
app.post('/posts', async (req,res)=>{
let db = connect();
let posts = req.body;
let result = await db.collection('posts').insertOne(posts);
})
Here is the exact error I'm getting:
UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function
at _callee$ (C:\Users\Jan\Desktop\Webshop\posts\src\/index.js:21:33)
at tryCatch (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:294:22)
at Generator.next (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:119:21)
at asyncGeneratorStep (C:\Users\Jan\Desktop\Webshop\posts\src\index.js:11:103)
at _next (C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:194)
at C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:364
at new Promise (<anonymous>)
at C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:97
at C:\Users\Jan\Desktop\Webshop\posts\src\/index.js:16:1

Database Saying Undefined Bindings When Compiling First Query

I was developing a backend with a SQLite3 and I deployed to heroku with postgresQL, the databse worked fine when it was in development, everything worked as expected and now I'm getting an error stating
2019-02-22T11:51:48.768183+00:00 app[web.1]: error Error: Undefined
binding(s) detected when compiling FIRST query: select * from "users"
where "id" = ? limit ?
2019-02-22T11:51:48.768200+00:00 app[web.1]: at QueryCompiler_PG.toSQL
(/app/node_modules/knex/lib/query/compiler.js:85:13)
However, there are no undefined bindings
My schema looks like
exports.up = function (knex, Promise) {
return knex.schema.createTable('users', users => {
users.increments('id')
users.string('name').notNullable();
users.string('email').notNullable();
users.string('username').notNullable();
users.string('password').notNullable();
users.string('role').notNullable();
})
};
The Query looks like
router.post('/signup', (req, res) => {
const user = req.body;
const hashedPass = bcrypt.hashSync(user.password, 12)
user.password = hashedPass;
var username = user.username
db.insertUser(user)
.then(ids => {
const id = ids[0];
db.findByID(id)
.then(user => {
const token = (newToken(user));
res.status(200).json({ id: user.id,
username:username,token:token});
})
.catch(err => {
console.log("error", err);
res.status(500).json({ error: 'Something went wrong' })
})
})
.catch(err => {
res.status(500).send(err);
});
});
Lastly, the helper function is...
findByID: (id) => {
return db('users').where('id', id).first();
}
Do you know what would be causing such an error, I have tried to search for it on here, and Google and can't find it. Thank you much in advance!

new Promise not allowing required types from mongo callback

I have a function that reads from mongo and returns the operation as a promise. The issue I'm facing is that the collection in mongo has a requiredProp and _id that are 100% in every record so they are not optional keys. Typescript for some reason is returning an error at runtime (below). I've tried to typescast result all the ways I know and nothing worked.
The only thing that did work was adding ? for both _id and requiredProp.
Example:
export interface MongoRequest {
_id: MongoObjectId;
requiredProp: boolean;
optionalProp?: boolean;
}
async function read (
query: MongoRequestQuery,
mongo: any,
): Promise<MongoRequest> {
const m = mongo.collection(MongoCollections.REQUESTS);
return new Promise((resolve, reject) => {
try {
return m.findOne(query, (err, result) => {
if (err) return reject(err);
if (result === null) return reject(new Error(`null mongo ${MongoCollections.REQUESTS}`));
return resolve(result);
});
} catch (e) {
return reject(e);
}
});
}
src/MongoRequests.ts (142,5): Type '{}' is not assignable to type 'MongoRequest'.
Property '_id' is missing in type '{}'. (2322)
Why is it that typescript is returning this error at runtime? How can I have required properties in the mongo type?

ObjectId is not defined while deleting from mongoDb using meanstack

I am trying to delete the entry from MOngoDb by using MEAN STACK with ANgular 4.(New to this technology)
typescript:
deleteitem(id){
let deleteresult;
let itemid = id;
this.dataService.deleteitem(itemid)
.subscribe(res =>deleteresult =res,
err => this.apiError = err,
)
};
dataservice:
deleteitem(itemid): Observable<any>{
let data =new URLSearchParams();
data.set('deleteId', itemid);
console.log(data.toString());
return this.http.post(URL, data.toString())
.map(res=> res.json())
.catch((error:any) => Observable.throw('Server Error To delete the item'));
}
Router.js
const ObjectID = require('mongodb').ObjectID;
router.post('/deleteitem', function(req, res){
MongoClient.connect('URL',function(err, client){
if (err) throw err;
var myDB = client.db('DbName');
var collection = myDB.collection('collectionName');
console.log(req.body);
//var objectId = collection.getObjectId();
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
{
res.send((result==1)?{msg:deleted} : {msg:"error:"+ err});
}});
})
})
Error:
ObjectId is not defined.
Also the console.log(req.body) gives a "{}" value. Not sure why.
But console.log(data.toString()); in the dataservice gives the value of intended _id to be removed from MongoDb.
Try using data instead of data.toString() in
return this.http.post(URL, data.toString())
This will give you output value in console.log(req.body);
Also, try replacing the below line of code
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
with
collection.deleteOne({_id: new mongodb.ObjectID(req.body.deleteId)}, function(err, result)
You need to create a new instance of mongodb here.
Hope this works.

GraphQL x MongoDB

I'm trying to read some data from a mongodb database with graphql and mongoose but everytime I query the db it returns null but no error is thrown.
Here's the code:
// Controller.js
exports.user_read = function(id) {
return new Promise((resolve, reject) => {
Contact.findById(id, function(err, user) {
err ? reject(err) : resolve(user);
}
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
contact.user_read(id)
}
...
Any tips and help would be appreciated.
P.S. This also seems to be happening with all my queries which take the same Promise format in the controller.js file.
You need to await contact.user_read(id). Without the await, you are simply sending back a Promise. It's most likely pending when it is returned, therefore the null return.
Including Daniel Rearden's suggestion to get rid of the extra Promise, here's what your code would look like:
// Controller.js
exports.user_read = async id => {
return Contact.findById(id, (err, user) => {
err ? reject(err) : resolve(user);
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
return await contact.user_read(id)
}
...