Dear arangodb community,
How mature is arangojs? When I tried "Tutorial: Node.js (io.js) in 10 minutes", the exercises 1 thru 4 work as expected. But the 5 thru 10 failed. From the following exercise, I am getting
Database created: undefined
instead of
Database created: "mydb"
Thus the remaining exercises cannot continue, since the crucial object-bearing variable (mydb) is null. But, observing that "mydb" data base is correctly created in arangodb, my question is just related to the maturity of aragogojs (arangodb's Javascript driver). Or how do I fix it?
db.createDatabase('mydb', function(err, newdb) {
if (err) {
console.log('Failed to create database: %j',
err.message);
} else {
console.log('Database created: %j', newdb.name);
mydb = newdb;
}
});
Thanks
The announced, updated node tutorial using the 4.x version of arangojs is available now.
Creating a new database changed to:
db.createDatabase('mydb').then(
() => console.log('Database created'),
err => console.error('Failed to create database:', err)
);
All asynchronous methods in the ArangoDB driver return promises but you can also pass a node-style callback instead:
db.createDatabase('mydb', function (err) {
if (!err) console.log('Database created');
else console.error('Failed to create database:', err);
});
The Node tutorial is based on version 3.x of the arangojs driver. The driver has recently been updated to version 4.x, which contains a number of breaking API changes.
The tutorial will soon be updated to reflect these changes. In the meantime you can follow the tutorial by installing version 3 explicitly:
npm install arangojs#3
Related
I am using adapter-node and a mysql pool in a sveltekit web app.
Previously, using just nodejs and express and no sveltekit, I found I needed to shutdown the mysql pool connections cleanly or mysql could hang when restarting the app.
I had something like:
process.on('SIGINT', () => server.close(() => pool.end()));
How would I achieve the same result in a sveltekit app? Or is it not necessary (and why)?
I can see in the sveltekit implementation where it creates the server, but does not seem to have any way to access it so I can call close(). I don't think it would be safe to call pool.end() before the server closes.
I also couldn't find any discussion of graceful shutdown in the sveltekit docs. There was 1 github issue but it was closed over a year ago and that change has since been removed from the code.
I found a similar issue asked in the svelte github. It has no resolution, so there is likely no official solution yet. https://github.com/sveltejs/kit/issues/6841
Disclaimers at the time of writing this answer:
I am brand new to Svelte and SvelteKit and only a couple years into web development in general
SvelteKit is pre-1.0 and subject to change
I am not 100% sure this answer handles all cases
I am using adapter-node
SvelteKit currently recommends doing one-time setup code in src/hooks.server.ts. So when talking about graceful shutdown, I will only worry about shutting down the things I setup in src/hooks.server.ts.
The brief answer is to set up process.on() handlers for exit and SIGINT that do any required cleanup.
An example for setting up and shutting down a mysql database pool when using adapter-node:
// src/hooks.server.ts
// One time setup code
await import('./db.js');
// ... remaining hooks.server.ts code
// src/db.ts
import { PRIVATE_MYSQL_PASSWORD } from '$env/static/private';
import type { Pool, PoolConnection, MysqlError } from 'mysql';
import { createPool } from 'mysql';
const pool = createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: PRIVATE_MYSQL_PASSWORD,
database: 'my_db',
multipleStatements: false,
timezone: 'UTC',
dateStrings: ['DATE', 'DATETIME'],
});
process.on('exit', (code) => end_db_pool(pool));
process.on('SIGINT', () => end_db_pool(pool));
function end_db_pool(pool: any) {
pool.getConnection(function (err, connection) {
connection.query('select 1 from my_table;', function (err, rows) {
connection.release();
// pool.end() only works inside getConnection();
pool.end((err) => {
if (err) log('pool.end err: ' + err);
});
});
});
}
// ... remaining API for DB operations using the pool
Another solution I tried and might still be useful is to create a custom adapter. I copied the adapter-node code into my project and modified files/index.js for some experimenting. For now, I am using the code above and not a custom adapter-node.
I have created four postresql tables. I am using nodejs with knexjs as a query builder.
I can create and execute migrations with the command line without any problems. Now I want to run migrations via Javascript. How can I proceed with this?
Here is my code: -
module.exports.runDBMigrations = async () => {
knex.schema.hasTable(USERS_DB_NAME).then(function (exists) {
if (!exists) {
//Execute migrations to create users tables
}
})
.catch(e => {
console.log("Error creating tables: ", e);
})
knex.schema.hasTable(POSTS_DB_NAME).then(function (exists) {
if (!exists) {
//Execute migrations to create posts tables
}
})
.catch(e => {
console.log("Error creating tables: ", e);
})
knex.schema.hasTable(LIKES_DB_NAME).then(function (exists) {
if (!exists) {
//Execute migrations to likes users tables
}
})
.catch(e => {
console.log("Error creating tables: ", e);
})
knex.schema.hasTable(FOLLOWERS_DB_NAME).then(function (exists) {
if (!exists) {
//Execute migrations to create followers tables
}
})
.catch(e => {
console.log("Error creating tables: ", e);
})
}
Hi,
Couple days I was sorrounding about how to run migrations and seeds when Server is starting.
Doing some researchs adn reading the Knex documentation, this is the solution what I reach to. Maybe this can help you.
Stack
lib
version
nodejs
16.17.x
nodemon
^2.0.19
npm
8.19.x
knex
^2.3.0
express
^4.18.1
pg
^8.8.0
postgreSQL
14.5
typescript
^4.8.2
Solution
1. Create a void function runMigrations(). (I located in models/setup/) (you can name it as how you want)
This function will have the knex singleton calling for running the migrations and the seeds.
2. Runn all the pending migrations calling the knex migrate .latest() method
This method is a promise, so you can capture the success creation or the error in case something goes wrong.
In this part, you can run all the seeds calling the knex seed .run() method. You can this method in the first callback
Call the migrations method in your index or server file. In my case Is runMigrations() method.
Restart your server, so you can check if everything works fine.
If you go to the terminal you can check response status. I add some log response, in order to know if everything working fine.
Note
I provoque an error so you can check the resutl if something were bad
executing the migrations or seeds
Maybe you'll find or your found others alternative of solution, but if you reach to fix the issue and added a different way; Please share it as a comment, so we can exchange knowledge and see a different way how to solve this issue.
Regards
I have an external dll (that written in c#) which is responsible of connecting to my DB.
I"m using this dll in my node.js application (Javascript).
When connecting to MSS DB connection result is true, when connecting to Oracle db it constantly fails with no option to know what went wrong.
but if im connecting to the Oracle DB thru a test project (written in c#) in my visual studio , the result is true.
the problem accord only when i use the dll thru the nodejs.
How can I resolve this?
This are different databases and need different connection modules.
I would suggest writing a separate connection in node as it is really easy with the node-oracledb module:
var oracledb = require('oracledb');
oracledb.getConnection(
{
user : "hr",
password : "welcome",
connectString : "localhost/XE"
},
function(err, connection)
{
if (err) { console.error(err); return; }
connection.execute(
"SELECT department_id, department_name "
+ "FROM departments "
+ "WHERE department_id < 70 "
+ "ORDER BY department_id",
function(err, result)
{
if (err) { console.error(err); return; }
console.log(result.rows);
});
});
You need to install the module first using npm.
More info here: https://blogs.oracle.com/opal/entry/introducing_node_oracledb_a_node
I am currently building an api application that checks the status and gets information of various types of dbs(i.e. Mongo, MySQL) using Sailsjs such as users, depending on a user input. Here is a snippet of the code I am working on. The local host is just the test database I am connecting to, but in the future it will be supplied by the user.
var mp = require('mongodb-promise');
var MongoClient = require('mongodb');
mp.MongoClient.connect("mongodb://#localhost:27017/test")
.then(function(db){
db.getUsers().then(function(users){
res.ok(users);
})
})
.fail(function(err) {
console.log(err);
})
I am attempting to use promises for the async issue. The problem I am having is that it doesn't work. It tells me that that Object[object object] has no method 'getUsers'. I have searched and can't seem to find a solution that works.
If I change the function to the below, I get the some data back.
mp.MongoClient.connect("mongodb://#localhost:27017/IMS")
.then(function(db){
db.stats().then(function(stats){
return res.ok(stats);
})
})
.fail(function(err) {
console.log(err);
dbObject.vipUp = false;
})
I am not sure what the issue is or how to solve it.
What you are doing here is using the node native driver methods to connect and inspect the database. There is in fact "no such method" as .getUsers() here in this API or in fact in any other API.
The .getUsers() function is just a "shell helper" that is basically implemented like this:
function (args) {
var cmdObj = {usersInfo: 1};
Object.extend(cmdObj, args);
var res = this.runCommand(cmdObj);
if (!res.ok) {
var authSchemaIncompatibleCode = 69;
if (res.code == authSchemaIncompatibleCode ||
(res.code == null && res.errmsg == "no such cmd: usersInfo")) {
// Working with 2.4 schema user data
return this.system.users.find({}).toArray();
}
throw Error(res.errmsg);
}
return res.users;
}
So what you should be able to see here is that this normally wraps a "command" form, or otherwise falls back for compatibility with MongoDB 2.4 to querying the system.users collection on the current database.
Therefore, instead of calling a method that does not exist, you then need to use the .command() method instead:
mp.MongoClient.connect("mongodb://#localhost:27017/test")
.then(function(db){
db.command({ "usersInfo": 1}).then(function(users){
res.ok(users);
})
})
.fail(function(err) {
console.log(err);
})
Or in the case of connecting to a MongoDB 2.4 instance, then fetch from the .collection():
mp.MongoClient.connect("mongodb://#localhost:27017/test")
.then(function(db){
db.collection('system.users').find().toArray().then(function(users){
res.ok(users);
})
})
.fail(function(err) {
console.log(err);
})
At any rate, you really should be establishing the database connection elsewhere in your application ( or re-using the underlying driver connection from another store ), and then calling methods on the connection already establihed. This is always preferable to creating a connection on the request of the information you want to retrieve.
Also, recent versions of the node native driver support promises right out of the box. So there may be no need to configure in anything else, depending on how you intend to use it.
I installed 2.5.5 so that I can try the new "$out" operator to create new collections with aggregation results. My node adapter is mongodb#1.3.23. I don't have "allowDiskUsage" in my code, but I get this error:
Uncaught MongoError: unrecognized field 'allowDiskUsage'
What do I need to do to update my project to run 2.5.5?
From a simple test on the same driver version I do not see the same results:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost/test', function(err, db) {
if (!err) {
db.collection('data', function(err, collection) {
if (!err) {
collection.aggregate([
{$out: "another" },
],function(err, result) {
if (err) {
console.log(err);
}
db.close();
});
}
});
}
});
There is an option for allowDiskUse that can be passed to the runCommand call to aggregate, but this does not directly have an impact on the $out pipeline operator, as it is intended for allowing the stages to use disk storage rather than memory alone. The usage of $out as you will be aware is to put the results in an output collection rather than return a cursor object.
If the same code used by itself is causing the same problem, you should check your installed driver version. As of 1.3.23 with a MongoDB 2.5.5 server, this code works as expected.
If this code passes, then there is likely some call or overriding module in your project that is implementing the option you specify in the error.