Get migrations to run on Waterlinejs standalone - sails.js

Node version: (18.0.0)
DB adapter & version (sails-postgresql#4.0.0):
I kindly require assistance to get migrations to run on waterline standalone version 0.15.0
My config is as follows:
module.exports = {
adapters: {
pg: require('sails-postgresql'),
mysql: require('sails-mysql'),
},
datastores: {
default: {
adapter: 'pg',
host: 'localhost',
port: 5432,
user: 'rcp',
password: 'rcp',
database: 'db_service',
isVersion12OrNewer: true,
},
mysql: {
adapter: 'mysql',
host: 'localhost',
port: 3306,
user: 'db',
password: 'db',
database: 'db_service',
},
},
};
My models:
module.exports = {
identity: 'pet',
datastore: 'default',
primaryKey: 'id',
migrate: 'alter',
attributes: {
id: {
type: 'number',
autoMigrations: { autoIncrement: true },
},
breed: { type: 'string' },
type: { type: 'string' },
name: { type: 'string' },
// Add a reference to User
owner: {
model: 'user',
},
},
};
module.exports = {
identity: 'user',
datastore: 'default',
primaryKey: 'id',
migrate: 'alter',
attributes: {
id: {
type: 'number',
autoMigrations: { autoIncrement: true },
},
firstName: { type: 'string' },
lastName: { type: 'string' },
// Add a reference to Pets
pets: {
collection: 'pet',
via: 'owner',
},
},
};
The bootstrap file:
const Waterline = require('waterline');
const config = require('./config');
const userModel = require('./models/user');
const petModel = require('./models/pet');
const userCollection = Waterline.Collection.extend(userModel);
const petCollection = Waterline.Collection.extend(petModel);
const waterline = new Waterline();
waterline.registerModel(userCollection);
waterline.registerModel(petCollection);
waterline.initialize(config, function (err, ontology) {
if (err) {
console.error(err.message);
return;
}
// Tease out fully initialized models.
let User = ontology.collections.user;
let Pet = ontology.collections.pet;
// Since we're using `await`, we'll scope our selves an async IIFE:
(async () => {
// First we create a user
const user = await User.create({
firstName: 'Neil',
lastName: 'Armstrong',
});
// Then we create the pet
const pet = await Pet.create({
breed: 'beagle',
type: 'dog',
name: 'Astro',
owner: user.id,
});
// Then we grab all users and their pets
const users = await User.find().populate('pets');
console.log(users);
})()
.then(() => {
// All done.
})
.catch((err) => {
console.error(err.message);
}); //_∏_
});
My package.json:
{
"name": "db-service",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon index.js"
},
"dependencies": {
"sails-mysql": "^2.0.0",
"sails-postgresql": "^4.0.0",
"waterline": "^0.15.0"
},
"devDependencies": {
"nodemon": "^2.0.18"
}
}
The issue I am facing is that when I run the bootstrap file, I get the error below:
Unexpected error from database adapter: relation "public.user" does not exist
Any assistance on this is highly appreciated.
Error Stack:
OperationalError [AdapterError]: Unexpected error from database adapter: relation "public.user" does not exist
at callback (/Users/.../Downloads/musings/db-service/index.js:20:27)
... 20 lines matching cause stack trace ...
at Connection.emit (node:events:539:35) {
cause: Error [AdapterError]: Unexpected error from database adapter: relation "public.user" does not exist
at callback (/Users/.../Downloads/musings/db-service/index.js:20:27)
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline.js:731:14
at /Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:952:25
at iteratorCallback (/Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:997:17)
at /Users/.../Downloads/musings/db-service/node_modules/async/dist/async.js:847:20
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline/utils/system/validate-datastore-connectivity.js:42:14
at /Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:954:24
at handlerCbs.success (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:814:26)
at Object.releaseConnection (/Users/.../Downloads/musings/db-service/node_modules/machinepack-postgresql/machines/release-connection.js:79:18)
at wrapper (/Users/.../Downloads/musings/db-service/node_modules/#sailshq/lodash/lib/index.js:3282:19)
at parley.retry (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:1076:19)
at parley (/Users/.../Downloads/musings/db-service/node_modules/parley/lib/parley.js:140:5)
at Object.runFn [as releaseConnection] (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:461:23)
at /Users/.../Downloads/musings/db-service/node_modules/waterline/lib/waterline/utils/system/validate-datastore-connectivity.js:35:27
at /Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:954:24
at handlerCbs.success (/Users/.../Downloads/musings/db-service/node_modules/machine/lib/private/help-build-machine.js:814:26)
at PendingItem.cb [as callback] (/Users/.../Downloads/musings/db-service/node_modules/machinepack-postgresql/machines/get-connection.js:87:20)
at BoundPool._acquireClient (/Users/.../Downloads/musings/db-service/node_modules/pg-pool/index.js:298:21)
at /Users/.../Downloads/musings/db-service/node_modules/pg-pool/index.js:270:21
at Connection.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg/lib/client.js:253:7)
at Object.onceWrapper (node:events:642:26)
at Connection.emit (node:events:539:35) {
adapterMethodName: 'create',
modelIdentity: 'user',
raw: error: relation "public.user" does not exist
at Parser.parseErrorMessage (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 110,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1363',
routine: 'parserOpenTable'
}
},
isOperational: true,
adapterMethodName: 'create',
modelIdentity: 'user',
raw: error: relation "public.user" does not exist
at Parser.parseErrorMessage (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/.../Downloads/musings/db-service/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 110,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1363',
routine: 'parserOpenTable'
}
}

Related

How to fix 'When using `sails-mongo`, primary keys MUST have `columnName: '_id'`'

I'm using:
"sails": "1.2.1",
"sails-mongo": "1.0.1"
when i get documents of a mongodb collection, i've got error like this:
In model `archive`:
debug: The default primary key attribute (`id`) is not set up correctly.
debug: When using `sails-mongo`, primary keys MUST have `columnName: '_id'`,
debug: and must _not_ have `autoIncrement: true`.
debug: Also, in most cases (unless `dontUseObjectIds` has been set to `true` for the model),
debug: then the `type` of the primary key must also be `string`.
sails.config.datastores.js
module.exports.datastores = {
default: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'test',
}
};
sails.config.models.js
module.exports.models = {
migrate: 'safe',
attributes: {
createdAt: { type: 'number', autoCreatedAt: true, },
updatedAt: { type: 'number', autoUpdatedAt: true, },
id: { type: 'string', columnName: '_id' },
},
dataEncryptionKeys: {
default: 'RWcFGJN8+at5E7eIwNCIQxkR7P0nRAW8Fg4c9tzwFTw='
},
cascadeOnDestroy: true
};
api.models.User.js
module.exports = {
tableName: 'user',
attributes: {
name: {
type: 'string'
},
age: {
type: 'number',
}
},
};
i've got error when i run api.controllers.UserController.js
module.exports = {
getUsers: function (req, res) {
let users = User.find();
return res.send(users);
},
};

MongoDB Not Finding Data : returns undefined

I have a datamodel named 'account' that stores a 'user'
var mongoose=require("mongoose");
mongoose.connect("mongodb://localhost/dataseed");
var db=mongoose.connection;
var accountSchema=mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
},
accountholder:{
type:String
},
cvv:{
type:String
},
expiryyear:{
type:String
},
expirymonth:{
type:String
},
accountnumber:{
type:Number
},
currentamount:{
type:Number
},
transferedamount:{
type:Number
},
withdrawnamount:{
type:Number
}
});
var account = module.exports = mongoose.model('account', accountSchema);
When I'm trying to found an account using the account.find() function. However it returns undefined when I try to access account.accountnumber
I'm querying my model as follows:
data.findById({"_id":req.params.id},function(err,data){
console.log("DATA.USER --------------------------------------------------");
console.log(data.user);
if(err)console.log(err);
else{
acessToken.create({user:req.user,data:req.params.id,token:token},function(err,acess){
if(err)console.log(err);
else{
console.log("ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss");
console.log(acess.user);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else
{
console.log("------------------------------------------------------------------------------------TYPE OF USER ID: " + typeof(req.user._id));
account.find({"user":req.user},function(err,d){
if(err)console.log(err)
var amount=d.currentamount-data.price;
var transferedamount=d.transferedamount+data.price;
console.log("Amount: "+amount); // NaN
account.findByIdAndUpdate({user:req.user},{currentamount:amount,transferedamount:transferedamount},function(err,update){
if(err)console.log(err);
console.log('Email sent: ' + info.response);
//getUsername of seller
// console.log(data.user)
user.findById({"_id":data.user},function(err,seller){
if(err){
console.log(err);
}else{
var buyer = req.user.username;
var seller = seller.username;
var priceOfData = data.price;
//ccNumber undefined
var ccnumber = d.accountnumber;
console.log("Buyer Name " +buyer);
console.log("Seller Name " +seller);
console.log("Price " +priceOfData);
console.log("Purchased on Credit Card Number " +ccnumber);
res.render('buyer/sold.ejs');
}
});
});
});
}
});
}
});
}
});
Models "data" and "acessToken" are used for finding a product and generating an access token of the purchased product.
This is the output im getting on my console.
5ca9ae4c044bab18588edf5b
ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss
5cd4cc83c3c65514c61ae4f3
------------------------------------------------------------------------------------TYPE OF USER ID: object
Amount: NaN
{ CastError: Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"
at MongooseError.CastError (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schema/objectid.js:232:11)
at ObjectId.SchemaType.applySetters (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:845:12)
at ObjectId.SchemaType._castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1248:15)
at ObjectId.SchemaType.castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1238:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1217:15)
at cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/cast.js:252:34)
at Query.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4334:12)
at castQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4186:18)
at Query._findAndModify (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:3203:23)
at Query.<anonymous> (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:2830:8)
at Query._wrappedThunk [as _findOneAndUpdate] (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/ubuntu/workspace/DataSeed/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"',
name: 'CastError',
stringValue: '"{ user: 5cd4cc83c3c65514c61ae4f3 }"',
kind: 'ObjectId',
value: { user: 5cd4cc83c3c65514c61ae4f3 },
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
Schema: [Object],
model: [Function],
plugins: [Object] },
modelName: 'account',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
'$internalEmitter': [Object],
_listening: false,
_events: [Object],
_eventsCount: 1,
_connectionOptions: [Object],
name: 'dataseed',
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
client: [Object],
'$initialConnection': [Object],
db: [Object] },
discriminators: undefined,
events:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined },
'$appliedMethods': true,
'$appliedHooks': true,
_middleware: Kareem { _pres: [Object], _posts: [Object] },
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
'$id': 7,
s: [Object],
_userProvidedOptions: {},
options: [Object],
'$globalPluginsApplied': true,
_requiredpaths: [] },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'accounts',
collectionName: 'accounts',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object] },
'$caught': true } }
Email sent: 250 2.0.0 OK 1557500841 d4sm5108746wrv.42 - gsmtp
Buyer Name murtaza1
Seller Name test1
Price 100
Purchased on Credit Card Number undefined
The problem with your code is that when you query your database you also need to call the populate method exposed by MongoDB and in particular Mongoose which I'm assuming you're using to query the DB. More info on Mongoose docs.
Why this happens? Well, since you're declaring using as a reference to your account Schema when Mongoose query the DB it only returns, without the populate method, the ID of the document referenced by that particular account Schema. Hope this helps you, cheers, sigfried

How to set up PostgreSQL database with associations between tables (foreign keys) with Sequelize

I'm using PostgreSQL, Sequelize, and Sequelize-cli.
Using sequelize-cli and some manipulation in an IDE I set up the following model and migration file (simplified for the example, I didn't include the "Users" migration file):
Model File
// models/annotation.js
module.exports = function (sequelize, DataTypes) {
var Annotation = sequelize.define('Annotation', {
userId: {
type: DataTypes.INTEGER,
references: {model: "User", key: 'id'},
},
url: DataTypes.STRING,
source: DataTypes.STRING,
body: DataTypes.TEXT,
exact: DataTypes.TEXT,
}, {
classMethods: {
associate: function (models) {
// associations can be defined here
Annotation.belongsTo(models.User, {foreignKey: "userId"});
},
},
});
return Annotation;
};
Corresponding migration file
// migrations/20161121050521-create-annotation.js
const User = require("../models/user");
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Annotations', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
references: {model: User, key: 'id'},
allowNull: false
},
...
Referenced Model
// models/user.js
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
title: DataTypes.STRING,
name: DataTypes.STRING,
email: DataTypes.STRING,
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
User.hasMany(models.Annotation, {foreignKey: "userId"});
}
}
});
return User;
};
I'm running the follow cli commands:
"dropdb -U postgres annotate && curl -XDELETE 'http://localhost:9200/_all'"
"createdb -U postgres annotate"
"node_modules/.bin/sequelize db:migrate"
When I migrate I get the following error:
SequelizeDatabaseError: relation "User" does not exist
From the documentation I was under the impression that Annotation.belongsTo(models.User would have been enough to establish the association, but when I did that my db tables didn't have any foreign key fields.
How can I establish tables with associations to one another?

OrientDB Server Error

I have a Problem with the orientjs Driver (https://github.com/orientechnologies/orientjs) or my OrientDB (v2.1.15). I have a Node.js Server and open a Connection to the Database Server like this:
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
username: 'root',
password: 'Orientdb'
});
Next I open a Database Connection and work with this DB, all works fine to this point. But if I want to list all Databases with the orientserver.list() Method I get this Error:
Unhandled rejection OrientDB.RequestError: Server user not authenticated.
at Operation.parseError (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:855:13)
at Operation.consume (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:446:35)
at Connection.process (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:383:17)
at Connection.handleSocketData (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:284:17)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:147:16)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:525:20)
To find the Issue I logged my Server at this Moment and get:
Server {
useToken: false,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
transport:
BinaryTransport {
domain: null,
_events: { reset: [Function: bound ] },
_eventsCount: 1,
_maxListeners: Infinity,
connecting:
Promise {
_bitField: 268566529,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: [Circular],
_boundTo: [Circular] },
closing: false,
retries: 0,
maxRetries: 5,
host: 'localhost',
port: 2424,
username: 'admin',
password: 'admin',
servers: [ [Object] ],
currentServer: 0,
enableRIDBags: true,
useToken: false,
token: <Buffer >,
sessionId: 62,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
connection:
Connection {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: Infinity,
host: 'localhost',
port: 2424,
socket: [Object],
logger: [Object],
enableRIDBags: true,
closing: false,
reconnectNow: false,
protocol: [Object],
queue: [],
writes: [],
remaining: null,
connecting: false,
protocolVersion: 32 },
skipServerConnect: true },
config:
{ get: [Function: bound ],
set: [Function: bound ],
list: [Function: bound ] },
domain: null,
_events:
{ reset:
[ [Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ] ],
error: [ [Object], [Object] ] },
_eventsCount: 2,
_maxListeners: Infinity }
As you can see the username and the Password is wrong. Someone know why this happen? Why I cant have Access to the Server after working with one DB on it?
*edit
Here is the Code of my nodejs Server (Not everything, just the important parts)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stringify = require('json-stringify-safe');
var routes = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport');
var expressSession = require('express-session');
var Strategy = require('passport-local').Strategy;
var users = {};
var databases = {};
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
httpPort: 2480,
username: 'root',
password: 'Orientdb'
});
passport.use(new Strategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req, username, password, cb) {
var sessID = req.sessionID;
var dbkey = username+"_"+req.params.database;
if(dbkey in databases) {
} else {
databases[dbkey] = orientserver.use({
name: req.params.database,
username: username,
password: password
});
}
users[sessID]= {id: sessID, username: username, database: dbkey};
return cb(null, users[sessID]);
}));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
});
app.get('/getAllProjects', function(req, res) {
//https://github.com/kriskowal/q
orientserver.list()
.then(function (dbs) {
var json = [];
dbs.forEach(function(value, index) {
json.push({"name": value.name});
});
//console.log('There are ' + dbs.length + ' databases on the server.');
res.status(200).send(json);
});
});
app.post('/:database',
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
res.redirect("/"+req.params.database);
});
So when I send the second Request to getAllProjects I get the Error.

Waterline, error when trying to create one-to-many association

I have these models:
// Material.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
source_info: {
type: 'string',
required: true
},
category: { model: 'category_mat' }
}
};
and:
// Category_Mat.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
material:{
collection: 'material',
via: 'category'
}
},
};
but when I run the app I get this error:
/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:82
throw new Error('Trying to access a collection ' + collection + ' that is
^
Error: Trying to access a collection category_mat that is not defined.
at ForeignKeys.findPrimaryKey (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:82:11)
at ForeignKeys.replaceKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:53:27)
at new ForeignKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/foreignKeys.js:30:10)
at new module.exports (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema.js:30:17)
at Waterline.initialize (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline.js:106:17)
at buildORM (/usr/local/lib/node_modules/sails/lib/hooks/orm/build-orm.js:48:15)
at Array.async.auto.instantiatedCollections [as 1] (/usr/local/lib/node_modules/sails/lib/hooks/orm/index.js:191:11)
at listener (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:465:46)
at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:419:17
at Array.forEach (native)
I used this documentation as reference:
http://sailsjs.org/#/documentation/concepts/ORM/Associations/OnetoMany.html
so I don't know what I'm missing or if there is a configuration that I have to do... any help?
Maybe it is because "category-mat" used on Material.js is not defined anywhere... try
// Category_Mat.js
module.exports = {
identity: 'category_mat',
attributes: {
name: {
type: 'string',
required: true
},
material:{
collection: 'material',
via: 'category'
}
},
};
If this works the only side effect is that even if you have config/globals.js/models set to "true", you won't be able to access the model in the controllers by using "Category_Mat". You will either have to use "sails.models.category_mat" or just "category_mat".