biggora / caminte Goto Github PK
View Code? Open in Web Editor NEWCross-db ORM for NodeJS
Home Page: http://www.camintejs.com/
License: MIT License
Cross-db ORM for NodeJS
Home Page: http://www.camintejs.com/
License: MIT License
Can i configure caminte to use mysql pool?
Hi everyone,
I have been trying 2 for days to figure the way the relations work with Caminte and I can't figure out.
I have the following Models :
var Class1 = schema.define(className, {
objectId : { type: schema.String, unique: true, index: true },
createdAt : { type: schema.Date, index: true },
updatedAt : { type: schema.Date, index: true }
}, {
primaryKeys: ["objectId"]
});
///// RELATIONS /////
Class1.hasMany(Class2, {as: 'otherclasses', foreignKey: "objectId"});
var Class2 = schema.define(className, {
objectId : { type: schema.String, unique: true, index: true },
createdAt : { type: schema.Date, index: true },
updatedAt : { type: schema.Date, index: true }
}, {
primaryKeys: ["objectId"]
});
I would like to be able to query all the objects in "otherclasses".
I'm trying this way : but obviously it doesn't sound to be the right way :
var query = instanceOfClass1.otherclasses.find();
query.limit(10);
query.run({}, function(err, results){
});
Can anyone help me out with that ?
Adapter : REDIS
Error thrown :
TypeError: undefined is not a function
at ModelConstructor.<anonymous> (node_modules/caminte/lib/abstract-class.js:1117:24)
at Function.<anonymous> (node_modules/caminte/lib/abstract-class.js:455:9)
at BridgeToRedis.<anonymous> (node_modules/caminte/lib/adapters/redis.js:390:9)
at node_modules/caminte/lib/adapters/redis.js:85:25
at node_modules/redis/index.js:592:9)
at RedisClient.return_reply (node_modules/redis/index.js:685:13)
at ReplyParser.<anonymous> (node_modules/redis/index.js:321:14)
at ReplyParser.EventEmitter.emit (events.js:95:17)
at ReplyParser.send_reply (node_modules/redis/lib/parser/javascript.js:300:10)
at ReplyParser.execute (node_modules/redis/lib/parser/javascript.js:211:22)
Schema:
var User = schema.define('user', {
//User details
steamid :{ type: String },
personaname :{ type: String },
avatar :{ type: String },
openID :{ type: String}
// Other unrelated schema
[...]
});
Search DB
// Should be false, returns true
User.find({'steamid' : '76561198150261243'}, function (err, doc) {
console.log(doc);
if (!doc) {
console.log('creating user, beeboobeeboop');
} else {
console.log('User already in DB');
}
})
The single collection has a 'steamid' of '76561198077435075'. And when running the User.find(), I am giving it a different ID to search (76561198150261243). However, the doc still returns the first entry for steamid 76561198077435075
I'm using firebird adapter, but when I try Model.find().where('field').like('value')
, it seens not work, it return all rows.
Hi! I have a class containing 1,000,000+ records with the following properties start_of_life, end_of_life, hist_id. hist_id is shared among different versions of a record. The following query "select min(start_of_life), max(end_of_life), hist_id from SomeVertex group by hist_id" causes the server to throw an exception (SEVERE Internal server error: java.net.SocketException: Socket closed [ONetworkProtocolHttpDb])
Orientdb versions: 2.0-M2, 2.0-M3
Any ideas or advice?
what are all the schema types? Do you support Array of integers? Array of strings? Enum?
If yes, how?
Conflict with https://github.com/cheeriojs/cheerio
TypeError: Cannot redefine property: length
at Function.defineProperty (native)
at \node_modules\caminte\lib\abstract-class.js:24:24
at Array.forEach (native)
at Function.Object.defineProperty.value (\node_modules\caminte\lib\abstract-class.js:21:15)
at Object.<anonymous> (\node_modules\cheerio\lib\cheerio.js:99:3)
Problem in
Object.defineProperty(Object.prototype, "extend", {
enumerable: false,
value: function(from) {
var props = Object.getOwnPropertyNames(from);
var dest = this;
props.forEach(function(name) {
if (name in dest) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(dest, name, destination);
}
});
return this;
}
});
it will be nice to add custom sql command query execution.
The model's save() method does not update because the model's id is not being passed in data to the adapter's own save() method.
Example:
var caminte = require('caminte'),
Schema = caminte.Schema,
schema = new Schema('sqlite3', {database: ':memory:'}),
Foo = schema.define('foo', {
bar: { type: schema.String}
},{
primaryKeys: ['id'],
});
schema.on('connected', function(){
var f = new Foo({
bar: 'baz'
});
f.save(function(err, fnew){
if (err) throw err;
console.log('f saved', fnew);
fnew.bar = 'baaaaaaaaaaaaaaaaaaz';
fnew.save(function(err, fnewer){
if (err) throw err;
console.log('fnew saved', fnew);
});
});
});
Results in:
/.../foo.js:20
if (err) throw err;
^
Error: SQLITE_ERROR: no such column: undefined
I'll issue a pull request shortly.
More query api support?
Columns of type JSON result in objects being written as strings with some adapters (redis in my case), e.g.:
{"foo": "bar"}
yields:
"{\"foo\":\"bar\"}"
The immediate cause is that AbstractClass._forDB
method checks this.schema.adapter.name
(which is not always set inside adapters) against a pre-defined list of NoSQL drivers, from which redis
is absent.
I like to create my models with prototype methods and I'm a bit at a loss as to how this is supposed to be achieved with caminte
.
Currently my model looks like this
module.exports = function (schema) {
var Session = schema.define("Schema", {
expires: {type: String, default: ""},
userId: {type: String, default: ""},
token: {type: String, default: ""},
});
Session.prototype.lifetime = function () {
return 0; // + config.session.lifetime;
};
...
return Session;
But it's really clunky to declare everything in an anonymous function. And since I have multiple models I don't want to initialize the schema in each model
Hi, biggora
Thank you very much for caminte.js.
This is my first message on github in English.
I have a problem with the count API, please have a check whether it is a issue or not.
// count posts by user
Post.count({where: {userId: user.id}}, function(err, count){
// your code here
There is a [where] condition({userId: user.id}) in a json object in the first parameter, let's call this parameter a [filter].
AbstractClass.count = function (params, callback) {
if (stillConnecting(this.schema, this, arguments)) {
return;
}
if (typeof params === 'function') {
callback = params;
params = null;
}
params = buildQuery(params, this);
this.schema.adapter.count(this.modelName, callback, params); // passing parameter
MongoDB.prototype.count = function count(model, callback, filter) {
var cond = buildWhere(filter); // I got {where: {'$columnName':{gt: 999}}" here while I using a filter like {where: {'columnName':{gt: 999}}} in the step A
this.collection(model).count(cond, callback);
I saw most of count API in other adapter class, parameter like the [filter] in count API of MongoDB.js is a json object of where condition only, but not a filter object with a where condition.
AbstractClass.count = function (params, callback) {
...
this.schema.adapter.count(this.modelName, callback, params.where ? params.where : params);
please have a check on it.
Have a nice day.
node_modules/mongodb/lib/mongodb/connection/base.js:245 throw message; ^ TypeError: undefined is not a function
Details: jugglingdb/mongodb-adapter#27
Fixed and tested in latest version https://github.com/jugglingdb/mongodb-adapter/archive/v0.1.0.tar.gz
I've looked at the documentation, but I dont see examples related for Neo4j. Any chance there can be some example showing relationships and some of the advanced Cypher querying?
I am creating a cloud application. The application involves maintaining a database and so i have designed a table with the following schema :
create table connectioninfo
(
device_id integer primary key,
date_updated integer not null, unique(device_id)
);
The database used is sqlite3 and I am using caminte for performing database related operations. When I am trying to insert or update a record in the table, I am getting the following error :
{ [Error: SQLITE_ERROR: table connectioninfo has no column named id] errno: 1, code: 'SQLITE_ERROR' }
I don't have any field with name 'id' . Is it necessary to have a field with the name 'id' in each table ? Can't I have user defined auto increment primary keys ? If so, how ?
***/node_modules/caminte/lib/schema.js:217
this.adapter.define({
^
TypeError: Cannot call method 'define' of undefined
I want to use new datatype JSONB and original JSON type for postgresql 9.4 .
Coud you implement in caminte?
Thanks
Hello,
below of is a piece of code, please explain me what I'm doing wrong?
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "redis",
host : "localhost",
port : "6379"
};
var schema = new Schema(db.driver, db);
var User = schema.define('User', {
title: { type: schema.String, limit: 255 },
fname: { type: schema.String},
lname: { type: schema.String}
});
User.create({title: "dok", fname: "Max", lname: "Manus"}, function(err, data){
console.log(err, data);
})
The error i get is:
****/caminte/lib/abstract-class.js:114
if (BASE_TYPES.indexOf(type.name) === -1) {
^
TypeError: Cannot read property 'name' of undefined
How to fix this?
Best regards,
Mr. Love
The current adapter dosen't work with new mongodb driver. I indexed a couple of problems and, if nobody is already working on it, I could write a new adapter.
Let me know
orm.autoparts.updateOrCreate({where:{id:data.id}}, {need:0} , function(err, part)
-->>Error: parts: no indexes found for where impossible to sort and filter using
redis adapter
orm.autoparts.update({where:{id:data.id}}, {need:0} , function(err, part)
-->> Method update undefined for this adapter
Hi found several issue:
SQLite3.prototype.autoupdate = function (cb) {
var self = this;
var wait = 0;
Object.keys(this._models).forEach(function (model) {
wait += 1;
//self.queryAll('SHOW FIELDS FROM ' + this.tableEscaped(model), function (err, fields) {
self.queryAll('PRAGMA table_info(' + self.tableEscaped(model) + ')', function (err, fields) {
self.alterTable(model, fields, done);
});
});
this.tableEscaped // caused error no tableEscaped. 'this' was different context (not adapter instance)
//this should change to self
self.tableEscaped
SHOW FIELDS FROM <tablename> // is not supported by sqlite
use PRAGMA table_info(<tablename>> instead
By the way, the functions return fails:
{ [Error: SQLITE_ERROR: duplicate column name: name] errno: 1, code: SQLITE_ERROR' }
Hi, my name is Alan and I've a problem using SQL databases. Caminte force that my tables have an "id" field and I do not use the default name. How can I fix this?
Best Regards
Hello
After hours of searching through the documentation of why my OR was causing an SQL error I found a bug in the mysql.js file (https://github.com/biggora/caminte/blob/master/lib/adapters/mysql.js)
At line 563 you can find this line of code:
return 'WHERE ' + orop + cs.join(' AND ');
But when using a combination of AND and OR like this:
newsitem.find({where: {id: 217, or: [{department: 1}, {department: 2}]}}, function(error, items) {
});
it will result in
SELECT * FROM newsitem WHERE (department=1 OR department=2) id=217
It misses an AND. By changing line 563 in the mysql.js file to
var glue = or.length > 0 && cs.length > 0 ? 'AND' : '';
return 'WHERE ' + orop + glue + cs.join(' AND ');
will fix the error
Complex statements like
SELECT * FROM newsitem_view WHERE (
(showfrom < "2013-11-20 15:18:24" AND showuntil > "2013-11-20 15:16:16") OR
(showfrom IS NULL AND showuntil IS NULL) OR
(showfrom IS NULL AND showuntil > "2013-11-20 15:16:16") OR
(showuntil IS NULL AND showfrom < "2013-11-20 15:18:24")
) AND department=3
does not seem possible with CaminteJS, isn't it?
Hi,
How to use transactions?
Maybe looks like this:
schema.begin();
Model1.create()...
Model2.update()...
schema.commit() / rollback()
Thanks
Hi, i am using neo4j adapter, but for some reason i am not able to use relations
My user model
var userSchema = caminte.define('Users', { username: { type: String, length: 20 }, email: { type: String, length: 65 }, password: { type: String, length: 12 }, activated: { type: Number}, account_type: { type: Number}, created_at: { type: Date, default: Date.now }, last_seen: { type: Date }, userId: { type: Number} }); userSchema.hasMany('Post', {as: 'posts', foreignKey: 'userId'}); module.exports = userSchema;
My post model
var postSchema = caminte.define('Post', { title: { type: String, length: 20 } }); postSchema.belongsTo('User', {as: 'author', foreignKey: 'userId'}); module.exports = postSchema;
My controller
User.create(userData, function(err, user){ if(user) { var post = user.posts.build({title: 'Hello world'}); post.create(console.log); return self.redirect('/activated'); } });
All other methods like Create, All, are working but if i define a relation, i get the following error
Cannot call method defineForeignKey
And its refering to user model on line 14 which is
userSchema.hasMany('Post', {as: 'posts', foreignKey: 'userId'});
Could you please give me hint?
Please add all the required dependencies to the package
I would like to recommend the support for OrientDB and ArangoDB don't mind contributing to this....
If the MongoDB adapter can't get a connection in one second, the setTimeout section of the define accesses the collection method to create indices. The collection method expects the this.client to have a value but the connection hasn't been established yet. Accessing the collection property of this.client results in an "TypeError: Cannot read property 'collection' of undefined". Here's the patch that added the this.client dependency:
ec6718c#diff-644d15beeed31d7ee15ce6aae98c3fc8
When I defined a model with the property 'email' which should be unique, I was able to create multiple entries that had the same value with no errors.
My model definition looks like this
var Model = schema.define('Model', {
email: { type: schema.String, "null": false, unique: true, index: true }
});
I am creating the instances like this
var model = new Model({ email: "[email protected]" });
model.save(function (err) {
err == null; //true
});
After doing the above twice, I query all entries like this
Model.all().run({}, function (err, results) {
err == null;
results == [
{ email: '[email protected]', id: 1 },
{ email: '[email protected]', id: 2 }
];
});
Unless there is a different way to specify a property as unique, this seems broken.
Hi,
I was getting TypeError: Cannot set property 'id' of undefined
on line 416 when calling all on a model using the redis adaptor. I had a quick look into the source and the culprit appears to be the line:
filter.where.id = {
gt: 0
}
I modified it locally to:
filter.where = {
id: {
gt: 0
}
and it appears to have worked successfully.
doing the following:
MyModel.all(function(err, models) {
console.log(err, models);
});
produces zero output - the console.log and callback is never called. However the following works:
MyModel.all({}, function(err, models) {
console.log(err, models);
});
So either there is a bug, or the documentation is wrong :)
It would be great if caminte
would create or support creation of the database on connection.
I was notified you going to raise funds on pledgie for http://www.camintejs.com/ which is copy of jugglingdb with removed copyrights. It's not acceptable.
I want to use replace function in update method like this command:
UPDATE ... SET field = replace(field,'cat','dog') WHERE ...
Could you please show me the way to do that?
Regards
Hello guys, I was looking for some way to select just some fields on my db.
I'm using MySQL, and my database has a field with big Text but I don't want to get it.
I was thinking about create 2 separated models, one with the big field an other without.
Anyone has any ideia about?
Thanks.
orm.prints.include(prints,'part',console.log())
show original prints. =(
Any plans to support eager loading? Thanks.
After initialization of two classes creating two mongodb connections, I attempt a findOne using on of the class. At this point, the call to constr.schema.adapter.all in the abstract-class.js#all function appears to be correct except the adapter.client is gone. There's no property even though the mongo class assigned it successfully (saw this in trace). I'll add more to this ticket as I discover more.
Hi,
if i am using connection pooling i get the error "no database selected". If i set pool to false in the settings it works.
the database option is set in the connection settings.
thanks and best
Hey,
is there a way for embedded documents?
On a redis backend, I've tried a combination of
postModel.findOne({ where: {}, order: 'id DESC'}, function(err, post) {
postModel.find().order('id', 'DESC').limit(1).run({},function(err, posts) {
postModel.all().order('id', 'DESC').limit(1).run({},function(err, posts) {
to get a max id on a large collection of posts with non-contigous IDs
They all take around 68 seconds to complete.
By if I manually run
sort s:post BY post:*->id DESC LIMIT 0 1
directly on redis, I can get the max id in under 2 secs
Is there another way I should be writing the query?
Using {where: {fld: {between: [1,10]}}}
Generates following SQL, ' fld BETWEEN 1,10 '
which should be ' fld BETWEEN 1 AND 10'
Changed the function parseCond in sqllite3.js:751
with
case 'between':
sqlCond += ' BETWEEN ';
val = self.toDatabase(props[key], conds[key]);
break;
Have created a pull request.
I got this message when call the method update of Model:
E:\projects\lounge-api\node_modules\caminte\lib\adapters\postgres.js:145
if (props[key] || key === 'id') {
^
ReferenceError: props is not defined
at E:\projects\lounge-api\node_modules\caminte\lib\adapters\postgres.js:145:
13
at Array.forEach (native)
at PG.update (E:\projects\lounge-api\node_modules\caminte\lib\adapters\postg
res.js:143:23)
at Function.update (E:\projects\lounge-api\node_modules\caminte\lib\abstract
-class.js:1018:29)
at E:\projects\lounge-api\app\controllers\UsersController.js:39:26
at E:\projects\lounge-api\node_modules\caminte\lib\abstract-class.js:542:17
at E:\projects\lounge-api\node_modules\caminte\lib\abstract-class.js:503:17
at PG. (E:\projects\lounge-api\node_modules\caminte\lib\adapters
postgres.js:191:13)
at null.callback (E:\projects\lounge-api\node_modules\caminte\lib\adapters\p
ostgres.js:56:9)
at Query.handleReadyForQuery (E:\projects\lounge-api\node_modules\pg\lib\que
ry.js:82:10)
It seems to be missing the definition of props.
Please check and fix it
Regards
I don't mind of using my code in your project while you keep my authorship in copyright. Please read copyright notice in jugglingdb project.
Доброго времени суток!
Создал модель, подключаю БД, а она ругается что таблица не создана. Судя по исходникам таблицы должны создаваться сами, но не создаются в чём проблема?
Table 'cryptoengine.block' doesn't exist
Модель
var Block = Schema.define('Block',{
number: {
type: Number,
required: true,
index: {
unique: true,
dropDups: true
}
},
difficulty: {
type: String
},
hash: {
type: String,
required: true,
index: {
unique: true,
dropDups: true
}
},
ended_at: {type: Date},
updated_at: {type: Date, default: Date.now},
created_at: {type: Date, default: Date.now}
});
Hi there, I'm going to implement support for Promise in my caminte fork and I''ll create pull request when ready. Is there any hints or idea from you?
This code
var Schema = require('caminte').Schema;
var schema = new Schema('sqlite', { database: 'test.db' });
var User = schema.define('User', {
name: String,
bio: Schema.Text,
approved: Boolean,
joinedAt: Date,
age: Number
});
var U = schema.models.User;
var u = new U({
name: "Herro my name is ..."
});
u.save(function(err, usr){
if(err){
console.log("Save err", err, err.stack);
return;
}
console.log("Saved:", usr);
U.count({}, function(err,c){
if(err){
console.log("Count err", err, err.stack);
return;
}
console.log("User has "+c+" objects.");
})
});
gives this output
/usr/local/bin/node sqlite.js
Save err { [Error: SQLITE_ERROR: no such table: User] errno: 1, code: 'SQLITE_ERROR' } Error: SQLITE_ERROR: no such table: User
Process finished with exit code 0
Am I doing something wrong ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.