Here is my customer_schema.js file:
up () {
this.create('customers', (table) => {
table.increments()
table.string('name', 30)
})
}
CustomerSeed.js:
class CustomerSeeder {
async run () {
const customer = await Factory
.model('App/Models/Customer')
.create()
console.log('customer: ')
}
}
The Customer.js model is "empty "
I run the migrations, all is Ok, but can not run the seeds : adonis seed throws this error message:
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlMessage: "Unknown column 'created_at' in 'field list'",
sqlState: '42S22',
index: 0,
sql:
"insert into `customers` (`created_at`, `name`, `updated_at`) values ('2019-03-04 20:01:17', 'Peter Walsh', '2019-03-04 20:01:17')" }
Why this happens? I did not even declare table.timestamps() in my schema file and :
describe customers;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
Edit:
static get createdAtColumn () {
return null;
}
static get updatedAtColumn () {
return null;
}
Add this 2 functions to your model, it should work :)
To add to the previous good answer, when you have lot of models as the application grows, you can automate the above solution instead of writing it as per model:
'use strict'
class NoTimestamp {
register (Model) {
Object.defineProperties(Model, {
createdAtColumn: {
get: () => null,
},
updatedAtColumn: {
get: () => null,
},
})
}
}
module.exports = NoTimestamp
Credit to Romain Lanz who showed me this solution.
Related
I have not been able to figure out the reason for the error I am getting. I'm not a Typescript ninja so maybe the error is obvious to someone here. My project is running micro services using Kubernetes and one of the services is throwing the following error when I run the project.
I have Googled as much as seems possible and found nothing helpful. The error is very specific to some attempts to make mongoose play nicely.
Thanks in advance.
My model file:
import mongoose from 'mongoose';
import { Order, OrderStatus } from './order';
interface TicketAttrs {
id: string;
price: number;
title: string;
}
export interface TicketDoc extends mongoose.Document {
id: string;
title: string;
price: number;
isReserved(): Promise<boolean>;
}
interface TicketModel extends mongoose.Model<TicketDoc> {
build(attrs: TicketAttrs): TicketDoc;
}
const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
price: {
type: Number,
required: true,
min: 0
}
}, {
toJSON: {
transform(doc, ret) {
ret.id = ret._id;
delete ret._id;
}
}
});
schema.statics.build = (attrs: TicketAttrs) => {
return new Ticket({
_id: attrs.id,
price: attrs.price,
title: attrs.title
});
};
/**
* Queries the orders to determine if a ticket is currently
* reserved.
*
* #returns boolean
*/
schema.methods.isReserved = async function() {
const existingOrder = await Order.findOne({
ticket: this,
status: {
$in: [
OrderStatus.Created,
OrderStatus.AwaitingPayment,
OrderStatus.Complete
]
}
});
return !!existingOrder;
};
const Ticket = mongoose.model<TicketDoc, TicketModel>('Ticket', schema);
export { Ticket };
The Error:
[orders] Compilation error in /app/src/models/ticket.ts
[orders] [ERROR] 11:43:04 ⨯ Unable to compile TypeScript:
[orders] src/models/ticket.ts(57,5): error TS2322: Type 'Document<any, {}>' is not assignable to type 'Pick<_LeanDocument, "id" | "_id" | "__v" | "title" | "price" | "isReserved"> | QuerySelector<Pick<_LeanDocument, "id" | ... 4 more ... | "isReserved">> | undefined'.
[orders] Type 'Document<any, {}>' is missing the following properties from type 'Pick<_LeanDocument, "id" | "_id" | "__v" | "title" | "price" | "isReserved">': title, price, isReserved
[orders]
Schema is a generic constructor, so try this:
new mongoose.Schema<TicketDoc>({...})
I brought the idea from here out.
model DataProvider {
id Int
name String
applications Application[]
##map("data_providers")
}
model Application {
id Int
name String
data_provider_id Int
running Boolean
data_providers DataProvider
##map("applications")
}
I want to get for each dataProvider how many applications with running = true there are.
DataProvider Application
----------------- -----------------------------------------------
id | name id | name | data_provider_id | running
----------------- -----------------------------------------------
1 | dp1 2 | app2 | 1 | true
-----------------------------------------------
3 | app3 | 1 | false
accordingly to achieve this result
dataProvider = {id: 1, name: 'dp1', _count: {applications: 1}}
I tried with query
this.prisma.dataProvider.findMany({
include: {
_count: {
select: {
applications: true
}
}
},
where: {
applications: {
some: {
running: {
equals: true
}
}
}
},
})
I guess I always get {applications: 2} as a result 2 to some, but I can use only some, every and none. What am I wrong?
I am a beginner with Jest, I am doing a program to study more JS. The tests work, but could this try / catch be replaced by exceptions? I believe that it is still not the best way to do this test with Jest.
import Category from "../app/models/Category.js"
describe("Test for category", () => {
it("error for null category", () => {
try {
new Category(null)
console.log("Error: category was created even as null name")
} catch (err) {
expect(err.message)
}
})
it("Error for empty category", () => {
try {
new Category(" ")
console.log("Error: category was created with an empty field")
} catch (err) {
expect(err.message)
}
})
it("Category registration", () => {
try {
new Category("Devops")
console.log("Category was created successfully!")
} catch (err) {
expect(err.message)
}
})
})
This is my class:
import { isEmpty, isNull } from "../validate.js"
export default class Category {
constructor(name) {
this.name = name
}
set name(name) {
if (isEmpty(name) || isNull(name)) throw new Error(`The category field needs to be filled`)
this._name = name
}
get name() {
return this._name
}
}
validate.js
export const isEmpty = value => !notEmpty(value)
export const isNull = value => value === null
Thanks for any help!
Use .toThrow(error?)
Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.
Category.js:
import { isEmpty, isNull } from './validate';
export default class Category {
constructor(name) {
this.name = name;
}
set name(name) {
if (isEmpty(name) || isNull(name)) throw new Error(`The category field needs to be filled`);
this._name = name;
}
get name() {
return this._name;
}
}
Category.test.js:
import Category from './Category';
describe('Test for category', () => {
it('error for null category', () => {
expect(() => new Category(null)).toThrowError('The category field needs to be filled');
});
it('Error for empty category', () => {
expect(() => new Category(' ')).toThrowError('The category field needs to be filled');
});
it('Category registration', () => {
const c = new Category('Devops');
expect(c._name).toBe('Devops');
});
});
unit test result with coverage report:
PASS src/stackoverflow/64217332/Category.test.js
Test for category
✓ error for null category (11ms)
✓ Error for empty category (2ms)
✓ Category registration (1ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 92.31 | 100 | 83.33 | 88.89 | |
Category.js | 85.71 | 100 | 66.67 | 83.33 | 13 |
validate.js | 100 | 100 | 100 | 100 | |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 5.502s, estimated 17s
I have used Sequelize with mysql database in my node js application. I want to fetch the value from the db and passed in to the bash script, consider the following code email is fetched from db and stored it in variable but I couldn't access outside of then function
desc users;
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| value | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.24 sec)
code:
User.findOne({where: {name: 'name'}}).then(function(user) {
var name = user.value
});
User.findOne({where: {name: 'email'}}).then(function(user) {
var email = user.value
});
User.findOne({where: {name: 'age'}}).then(function(user) {
var value = user.value
});
var child = exec('bash user.sh name age email')
How to access variables (name, email, age) outside then function in node js?
var child = exec('bash user.sh email')
User.findOne({where: {name: 'usr1'}}).then(function(user) {
var email = user.email;
console.log(child);
},child);
The database query runs asynchronously, So if you want to use any result from the query, you must write that code inside then.
For example -
User.findOne({where: {name: 'usr1'}})
.then(function(user) {
// Do your stuff here.
var email = user.email;
var child = exec('bash user.sh email');
});
The most intuitive solution would be to use async await
(async () => {
const email = await User.findOne({where: {name: 'usr1'}});
const child = exec('bash user.sh email');
})();
I'm getting the following error when trying to call .create() on a model from a Sails.js controller.
Here is my model, TemperatureReading.js:
module.exports = {
connection: 'mainDatabase',
tableName: 'TemperatureReading',
attributes: {
id: {
columnName: 'id',
type: 'integer',
minLength: 1,
primaryKey: true,
unique: true
},
deviceId: {
columnName: 'deviceId',
type: 'integer',
minLength: 1,
},
temperatureReading: {
columnName: 'temperatureReading',
type: 'string',
max: 150,
required: true
},
dateRecorded: {
columnName: 'dateRecorded',
type: 'string',
},
}
};
routes.js:
module.exports.routes = {
'get /enterSensorReading': 'MainController.getSensorReading'
};
MainController.getSensorReading:
getSensorReading: function (request, response) {
var temperatureReading = request.param('temperatureReading');
var date = new Date();
var dateRecorded = date.getDate() + "/"
+ (date.getMonth()+1) + "/"
+ date.getFullYear() + " "
+ date.getHours() + ":"
+ date.getMinutes() + ":"
+ date.getSeconds();
console.log(temperatureReading);
TemperatureReading.create({temperatureReading: temperatureReading, dateRecorded: dateRecorded}).exec(function(err, createdReading) {
if(err) {
response.send(err);
} else {
console.log('Created reading');
}
});
}
connections.js
module.exports.connections = {
mainDatabase: {
adapter: 'sails-mysql',
host: '127.0.0.1',
port: 3306,
user: 'myUser',
password: 'myPW',
database: 'MAIN'
}
};
And finally, my database structure:
TemperatureReading
------------------
id int(5) PK
deviceId int(5)
temperatureReading varchar(255)
date varchar(255)
Any ideas as to what is going wrong?
The database structure should be something like this:
mysql> describe TemperatureReading;
+--------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| deviceId | int(11) | YES | | NULL | |
| temperatureReading | varchar(255) | YES | | NULL | |
| dateRecorded | varchar(255) | YES | | NULL | |
| createdAt | datetime | YES | | NULL | |
| updatedAt | datetime | YES | | NULL | |
+--------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
It should be dateRecorded and not just date
If its a new app and you are creating the table from scratch, use add "migrate": "drop" in your model. This will automatically create the table for you. Make sure to remove this line next time you lift the server. If this does not solve the problem, then I don't see any issue with the code. I tested and it worked perfectly on my system. It might be possible that something messed up with your sails-mysql adapter. If fixing your database structure does not solve the problem, try this
npm uninstall sails-mysql
npm cache clear
npm install sails-mysql
Even more rigorous way would be:
rm -Rf node_modules
npm cache clear
npm install
Let me know if this solves the problem you are facing