duyluonglc / lucid-mongo Goto Github PK
View Code? Open in Web Editor NEWMongodb ODM for adonis framework
Mongodb ODM for adonis framework
Hi, is it possible to rename _id to id?
I've tried, but without any effect:
class MyModel extends Model {
...
static get primaryKey () {
return 'id'
}
...
}
Hi, do you have any roadmap for the next version? I think this project is the best mongodb ODM library and I hope to I could use it in other frameworks such as Express.js
Thank you!
It will be awesome if I can use it without AdonisJs, sometimes express.js is a better choice.
I am getting this error whenever i try to run this command ./ace migration:run
(node:15772) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: double colon in host identifier
i did all steps right but i don't know what to do to fix this error
const tour = Tour.with(['type']);
if (typeFilter != "") {
tour.where('active', 1).where('type_id', typeFilter)
}
else{
tour.where('active', 1)
}
yield tour.paginate(request.input('page', 1), 2);
Converting circular structure to JSON
Hi there,
I'm new to AdonisJS development, I came from background as Laravel developer, I want to ask if there any hybrid relationship available that we can make relationship from mongodb collection into mysql table (legacy database) using official Adonis Lucid?
Take a look on this repo for example:
laravel-mongodb
Is there a way to edit the timezone for the created_at and updated_at?
Branch | Build failing 🚨 |
---|---|
Dependency | adonis-ace |
Current Version | 3.0.7 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As adonis-ace is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
The new version differs by 5 commits.
84e9c93
Merge branch 'release-3.0.8'
941f609
chore(release): 3.0.8
da5e4e8
fix(command): use command.opts() over command._events
8d0ffda
chore(package): update sinon to version 2.0.0 (#48)
89dab62
fix(package): update node-exceptions to version 2.0.0 (#49)
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
When i refresh token JWT
TypeError: this._getQuery(...).whereHas is not a function\n at LucidSerializer.findByToken (/Library/WebServer/Documents/node_project/putty_adonis/node_modules/@adonisjs/auth/src/Serializers/Lucid.js:162:8)\n at JwtScheme.generateForRefreshToken (/Library/WebServer/Documents/node_project/putty_adonis/node_modules/@adonisjs/auth/src/Schemes/Jwt.js:304:49)
Hi, thanks for your help first.
I have a Order
model like this:
Just only one orders collection, not two collections.
{
"no": "A12333333",
"total": 46,
"items": [
{buyable_type: 'App/Models/Course', buyable_id: 'A7786887899E898F8', price: 19},
{buyable_type: 'App/Models/Course', buyable_id: 'A7786887899E898F9', price: 27},
]
}
How can I add a morph relation on items
like this:
buyable(){
return this.morphTo('App/Model', 'items.buyable_type', 'items.buyable_id')
}
so I can access buyable
objects of children?
Hi. I have products with custom, unique 6-chars ID (for example 123456
).
I added test product by MongoDB console:
db.products.insertOne({ _id: "123456", name: "Test Product" })
My Adonis files:
// routes.js
Route.group(() => {
Route.get('products/:id', 'ProductController.show')
}).prefix('v1')
// show method from ProductController.js
async show ({params, response}) {
const product = await Product.where('_id', params.id).fetch()
return response.json(product)
}
When I try to send a GET request http://127.0.0.1:3333/v1/products/123456
I get an error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
If I try to find it by Mongo console (db.products.find({_id: "123456"})
) it works fine.
How can I use in controller/router custom _id
?
It seems I can't use sum()
for relation?
code:
yield customer.transactions().sum('amount')
and I get the result of all records, without any where
condition.
query log:
mquery sum transactions {} { _id: '$undefined', sum: { '$sum': '$amount' } } +3ms
in Model
static get objectIdFields() {
return ['_id', 'timeline_id', 'type_id']
}
In Controller
//below query doesn't work
tours = yield Tour.with(['type']).where('type_id', typeFilter).paginate(request.input('page', 1), 20);
Lucid find() with([type]) returns the correct results.
Tour {
attributes:
{ _id: 59000f5c898d9a03481b5ed4,
name: 'Canada Ontario Trip',
desc: 'a marvellous trip suthi parka porom',
active: 1,
adults: 10,
children: 0,
type_id: '590819ce4671a409ac276589',
price: 50,
discounted_rate: '10%',
popular: '',
featured: '',
schedules: [ [Object], [Object] ],
created_at: moment.utc("2017-04-26T03:09:14.943+00:00"),
updated_at: moment.utc("2017-04-26T03:09:14.943+00:00") },
original:
{ _id: 59000f5c898d9a03481b5ed4,
name: 'Canada Ontario Trip',
desc: 'a marvellous trip suthi parka porom',
active: 1,
adults: 10,
children: 0,
type_id: '590819ce4671a409ac276589',
price: 50,
discounted_rate: '10%',
popular: '',
featured: '',
schedules: [ [Object], [Object] ],
created_at: moment.utc("2017-04-26T03:09:14.943+00:00"),
updated_at: moment.utc("2017-04-26T03:09:14.943+00:00") },
unsetFields: [],
transaction: null,
relations:
{ type:
Type {
attributes: [Object],
original: [Object],
unsetFields: [],
transaction: null,
relations: {},
exists: true,
frozen: false,
eagerLoad: [Object] } },
exists: true,
frozen: false,
eagerLoad:
EagerLoad {
withRelations: [],
withNestedRelations: {},
relationsScope: {},
nestedRelationsScope: {} } }
then .with('categories')
works not as expected:
I've read your source code, it seems you mark every related document with only ONE parent primary key ,so if there are two or more parent documents have some same children, it works not as expected.
/lucid-mongo/src/LucidMongo/Relations/ReferMany.js:84
related.$sideLoaded[`refer_${this.primaryKey}`] = parent[this.primaryKey]
let settings = yield Setting.where({parent_id: {not: null}}).fetch()
hope to support more methods. thanks.
Can you development the Hook afterPaginate like Lucid
Lucid Mongo: this._events = ['create', 'update', 'delete', 'restore', 'find', 'fetch']
Lucid: this._events = ['create', 'update', 'delete', 'restore', 'find', 'fetch', 'paginate']
So when i created afterPaginate Hook i got error: "message": "E_INVALID_PARAMETER: paginate is not a valid hook event",
///Lucid Model
class Tour extends Lucid {
static get objectIdFields() {
return ['_id', 'type_id', 'main', 'thumb', 'slides']
}
thumb(){
return this.belongsTo('App/Model/Media', '_id', 'thumb');
}
main(){
return this.belongsTo('App/Model/Media', '_id', 'main');
}
type() {
return this.belongsTo('App/Model/Type')
}
}
/////////////////////////////// Controller
const cart = yield Cart.with('items', 'items.tour', 'items.tour.main').find('5922d0c1d7b97d3e70ea5a56');
res.json(cart);
My Database
{
"_id": {
"$oid": "590036b549b95b119cf051df"
},
"name": "Lovely Trip",
"desc": "a marvellous trip suthi parka porom",
"active": 1,
"adults": 5,
"children": 0,
"type_id": {
"$oid": "590819cd4671a409ac276588"
},
"thumb": {
"$oid": "5918540052a6632e840350b2"
},
"main": {
"$oid": "5918540052a6632e840350b2"
},
"roosh": {
"love": "asdasdasd"
},
"slides": [
{
"$oid": "59185779f56a722840f7c461"
},
{
"$oid": "5918540052a6632e840350b2"
},
{
"$oid": "59185ddb89a2153ac4b2a4c8"
}
],
"price": 400,
"discounted_rate": "43%",
"popular": true,
"featured": false,
"schedules": [
{
"date": "2017-04-24",
"time": "17.30",
"duration_in_mins": 60
},
{
"date": "2017-04-27",
"time": "15.30",
"duration_in_mins": 300
}
],
"created_at": {
"$date": "2017-04-26T05:57:07.797Z"
},
"updated_at": {
"$date": "2017-04-26T05:57:07.797Z"
}
}
This relationship doesn't work, and it doesn't show thumb, main and slides in final results too. Cart.with('items', 'items.tour', 'items.tour.type')
but it works well with type.
Results
{
"_id": "5922d0c1d7b97d3e70ea5a56",
"items": [
{
"_id": "592159774b920a14806ab1cf",
"tour_id": "59000fc90fc97b0968de5d46",
"adults": 1,
"price": 400,
"created_at": "2017-05-21T09:10:15.864Z",
"updated_at": "2017-05-21T09:10:15.864Z",
"tour": {
"_id": "59000fc90fc97b0968de5d46",
"name": "Lovely Trip",
"desc": "a marvellous trip suthi parka porom",
"active": 1,
"adults": 5,
"children": 0,
"type_id": "590819cd4671a409ac276587",
"price": 110,
"discounted_rate": "10.00",
"popular": true,
"featured": false,
"schedules": [
{
"date": "2012-12-30",
"time": "17.30",
"duration_in_mins": 60
},
{
"date": "2012-02-30",
"time": "15.30",
"duration_in_mins": 300
}
],
"thumb_id": "5918540052a6632e840350b2",
"created_at": "2017-04-26T03:11:03.299Z",
"updated_at": "2017-04-26T03:11:03.299Z",
"discounted_price": 100
}
},
{
"_id": "592159774b920a14806ab1d0",
"tour_id": "590036b549b95b119cf051df",
"adults": 5,
"children": 3,
"price": 1000,
"created_at": "2017-05-21T09:10:15.865Z",
"updated_at": "2017-05-21T09:10:15.865Z",
"tour": {
"_id": "590036b549b95b119cf051df",
"name": "Lovely Trip",
"desc": "a marvellous trip suthi parka porom",
"active": 1,
"adults": 5,
"children": 0,
"type_id": "590819cd4671a409ac276588",
"roosh": {
"love": "asdasdasd"
},
"price": 400,
"discounted_rate": "43%",
"popular": true,
"featured": false,
"schedules": [
{
"date": "2017-04-24",
"time": "17.30",
"duration_in_mins": 60
},
{
"date": "2017-04-27",
"time": "15.30",
"duration_in_mins": 300
}
],
"created_at": "2017-04-26T05:57:07.797Z",
"updated_at": "2017-04-26T05:57:07.797Z",
"discounted_price": 228
}
}
],
"uniqueHash": "Rooshan",
"user_id": "58eb4b61ace74303d41b803b",
"created_at": "2017-05-22T11:51:29.074Z",
"updated_at": "2017-05-22T11:51:29.074Z"
}
PS: there are modifications in results, due to checking.
My problem is as follows:
I have these three tables:
news
class_codes
class_code_new
So News have many ClassCodes and ClassCodes have many News, so a "belongsToMany" relationship ( I have added the belongsToMany configuration methods on each model. I only need it from the "New" model to get the class codes for each news).
I have lets say News 1 and 2 and I have only Class Code 1. Each of the News have this class code, so the pivot table looks something like this:
_id, new_id, class_code_id
1, 1, 1
2, 2, 1
When I make a query like this:
New.with('classCodes').fetch()
or New.with('classCodes').paginate(1, 2)
, as a result I get an array of news ( so New 1 and 2 ), but only New 1 has the class codes attached. The class codes in the second New is empty. This is what the results should be like:
[
{
"_id": "59f1d4d01f1f6243f3ae9b4c",
"title": "New 1",
"classCodes": [
{
"_id": "59f74f81bf938e8aca911915",
"name": "Class Code 1"
}
]
},
{
"_id": "59f751aebf938e8aca911a17",
"title": "New 2",
"classCodes": [
{
"_id": "59f74f81bf938e8aca911915",
"name": "Class Code 1"
}
]
}
]
and this is what I'm getting instead:
[
{
"_id": "59f1d4d01f1f6243f3ae9b4c",
"title": "New 1",
"classCodes": [
{
"_id": "59f74f81bf938e8aca911915",
"name": "Class Code 1"
}
]
},
{
"_id": "59f751aebf938e8aca911a17",
"title": "New 2",
"classCodes": []
}
]
Any idea why is this the case ?
BTW: I inserted them in the pivot table from the built in method create on the relationship, like this:
var news1 = New.first();
var news2 = New.last();
var classCode1 = ClassCode.first();
news1.classCodes().save(classCode1);
news2.classCodes().save(classCode1);
I am using the following code to acquire all registered users
const user = await User.all()
The return of this code is this:
{
"_id": "5a75ef1ddcd123280c12e49c",
"name": "Bryann Barbosa",
"email": "[email protected]",
"password": "$2a$10$5rYbEs9XdoRHaPeIer7rH.4/1zHTfu0G/1xA9IkqKz4eJZpBVxkvm",
"user_type": "administrator",
"address": "São José dos Campos",
"created_at": "2018-02-03 15:19:25",
"updated_at": "2018-02-03 15:19:25"
}
however, I want to hide the password field, or even more fields, if necessary, how can I do this using this library?
Branch | Build failing 🚨 |
---|---|
Dependency | mongodb |
Current Version | 2.2.29 |
Type | dependency |
This version is covered by your current version range and after updating it in your project the build failed.
mongodb is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪
The new version differs by 4 commits.
295fb3a
2.2.30
bd4bdf6
feat(MongoClient): add appname
to list of valid option names
7116ea4
fix(url-parser): ensure user options are applied to parsing
d127f67
Added test for passing appname as option
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
The readme mentions this project is still a work in progress, but version 1 has been released. How stable is this? Is it ready for production? If not, is there some sort of a roadmap?
Hi there,
I want to store authentication session to use later but instead I get this error:
Cannot store ObjectID data type to session store
here is my code in start/routes.js
:
await auth.attempt('[email protected]', 'secret')
and config in config/auth.js
:
authenticator: 'session',
session: {
serializer: 'lucid',
model: 'App/Models/User',
scheme: 'session',
uid: 'email',
password: 'password'
},
I'm using adonisjs 4.0 with lucid-mongo 2
I have two models, one for my "news" and one for my "suppliers". At the news I specified the relation like this:
suppliers(){
return this.referMany('App/Model/Supplier', "_id", "suppliers")
}
When I attach some supplier to a specific news it works well, so it saves it under the field "suppliers", but when I try to query it, it keeps giving me this message:
"message": "Cannot read property 'suppliers' of undefined",
This is how I'm querying it:
yield New.with('suppliers').first()
and this is how I'm saving it:
yield New.suppliers().attach(yield Supplier.first())
BTW: I had quite a similar issue with the "embeds" relationships.
this query fails with an error message of
path must be a string or object
const tours = yield
Tour.with(['type'])
.where(function (){
if (typeFilter != "") {
this.where('active', 1).where('type_id', typeFilter)
}
else{
this.where('active', 1)
}
})
.paginate(request.input('page', 1), 2);
Hey i wrote a hook so i could define field sanitization for models just before saving just like Django and other frameworks.
My Model has a method that returns an object of indicative (the validation library for adonis) rules.
sanitizationRules() {
return {
email: [
rule('normalize_email')
]
}
}
And i have a hook that a add to the beforeSave event
/**
* If the instance does not have set some values, it
* will set the defaul values if set
*
* @method
*
* @param {Object} instance
*
* @return {void}
*/
ValidatedModelHook.sanitize = async (instance) => {
/* We obtain the default values */
const validationRules = instance.sanitizationRules()
instance.$attributes = sanitize(instance.$attributes, validationRules)
}
And i add the hook like this:
static boot() {
super.boot()
this.addHook('beforeSave', 'ValidatedModel.defaults')
this.addHook('beforeSave', 'ValidatedModel.sanitize')
this.addHook('beforeSave', 'ValidatedModel.validate')
}
I think this could be useful to the framework if it could be integrated to the save functions, although it works fine at the hook level. Just hope this can be done and that i can be useful to you.
Branch | Build failing 🚨 |
---|---|
Dependency | mocha |
Current Version | 3.4.2 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As mocha is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
--forbid-only
and --forbid-pending
flags. Use these in CI or hooks to ensure tests aren't accidentally being skipped! (@charlierudolph)--napi-modules
flag (@jupp0r)The new version differs by 34 commits.
82d879f
Release v3.5.0
bf687ce
update mocha.js for v3.5.0
ec73c9a
update date for release of v3.5.0 in CHANGELOG [ci skip]
1ba2cfc
update CHANGELOG.md for v3.5.0 [ci skip]
065e14e
remove custom install script from travis (no longer needed)
4e87046
update karma-sauce-launcher URL for npm@5
6886ccc
increase timeout for slow-grepping test
2408d90
Make dependencies use older version of readable-stream to work around incompatibilities introduced by 2.3.0 on June 19th
68a1466
Try not clearing the env for debug in the integration test and see if that fixes Node 0.10 on AppVeyor; if need be, some other fix/workaround can be applied to handle whatever was up with debug without causing this issue
958fbb4
Update new tests to work in browser per test hierarchy reorganization
1df7c94
Merge pull request #2704 from seppevs/increase_test_coverage_of_mocha_js
1f270cd
Stop timing out (#2889)
27c7496
upgrade to [email protected]; closes #2859 (#2860)
50fc47d
fix CI; closes #2867 (#2868)
1b1377c
Add test for ignoreLeaks and fix descriptions
There are 34 commits in total.
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
I add used_at
to dates()
so that it can be displayed as date time, but when I querying data use await Voucher.where({used_at: null})
to find vouchers not be used, the logs of mquery is
mquery findOne vouchers { used_at: Invalid Date } { fields: undefined } +5ms
null
Hello again @duyluonglc , i found an interesting detail, the behavior of the models if i use find is differente if i search them with where and fetch.
My Models:
class Contact extends UserOwnedModel {
group() {
return this.belongsTo('App/Models/Group')
}
static get objectIDs() {
var list = super.objectIDs
return list.concat([
'group_id'
])
}
}
class Segmentation extends UserOwnedModel {
filters() {
return this.embedsMany('App/Models/Filter')
}
contacts() {
return this.referMany('App/Models/Contact')
}
}
My Controller:
/**
* Store
*
* @param {any} request
* @param {any} response
* @returns
*
* @memberOf EmailContentController
*
*/
async send({
request,
response,
instance,
params,
auth
}) {
const user = await auth.getUser()
var embedInstance = await instance.emailContents()
.find(params.embedId)
if (!embedInstance) {
throw ResourceNotFoundException.invoke(`Can not find model with id "${params.emailId}"`)
}
/* We find our email properties */
const properties = await user.properties().where({
is_email: true
}).fetch()
const emailDbFields = []
for (let i = 0; i < properties.length; i++) {
emailDbFields.push(properties.db_name)
}
const segmentationRefs = request.input('segmentations', [])
const emailList = [];
for (let i = 0; i < segmentationRefs.length; i++) {
const segmentationRef = segmentationRefs[i];
const segmentation = (await user.segmentations().find(segmentationRef))
const contacts = await segmentation.contacts().fetch()
for (let j = 0; j < contacts.length; j++) {
const contact = contacts[j];
for (const key in contact) {
if (contact.hasOwnProperty(key)) {
if (key in emailDbFields) {
emailList.push(contact[key])
}
}
}
}
}
const segmentations = (await user.segmentations().where({
"_id": {
"in": segmentationRefs
}
}).fetch()).rows
return response.apiUpdated(segmentations)
}
It gives me the following error:
{
"status": 500,
"message": "segmentation.contacts is not a function",
"traces": "TypeError: segmentation.contacts is not a function\n at EmailContentController.send (/home/francisco/Repositories/Nuviio/Mercurio/server-v2/app/Controllers/Http/Api/EmailContentController.js:134:43)\n at <anonymous>"
}
If i change the find line for the following code:
const segmentation = (await user.segmentations()
.where({
_id: segmentationRef
})
.fetch()).rows[0]
It works and does not give that error.
module.exports = class AdminUser extends Model {
static get objectIds(){
return ['_id', 'role_ids']
}
}
I store an array of roles objectIds in role_ids
, but it stores as plain string instead ObjectID
type to mongodb.
when i'm trying to logged in i find this error
here is my model
'use strict'
const Model = use('Model')
class User extends Model {
static boot () {
super.boot()
/**
* A hook to bash the user password before saving
* it to the database.
*
* Look at `app/Models/Hooks/User.js` file to
* check the hashPassword method
*/
this.addHook('beforeCreate', 'User.hashPassword')
}
/**
refreshTokens
orrememberToken
will be saved inside themodule.exports = User
and my controller function
async login ({ request,session, auth }) {
const test = await auth.attempt(request.input('email'),request.input('password'));
console.log(test)
// return 'Logged in successfully'
}
also config/auth.js
'use strict'
module.exports = {
/* |
---|
Authenticator |
-------------------------------------------------------------------------- |
|
| Authentication is a combination of serializer and scheme with extra
| config to define on how to authenticate a user.
|
| Available Schemes - basic, session, jwt, api
| Available Serializers - lucid, database
|
*/
authenticator: 'session',
/* |
---|
Session |
-------------------------------------------------------------------------- |
|
| Session authenticator makes use of sessions to authenticate a user.
| Session authentication is always persistent.
|
*/
session: {
serializer: 'lucid',
model: 'App/Models/User',
scheme: 'session',
uid: 'email',
password: 'password'
}
adonis support told me it's package error .... and the error is in serialize
Hi,
First, thank you for the great job you've done !
In Adonis v3.2.1, the API authentication provided by the official adonis-auth module does not work when using the adonis-lucid-mongodb module. It seems that there is several reasons and one of them is the "andWhere" method that is not implemented.
E_INVALID_MODEL_STATE: Cannot save empty User model
class IndexController {
* index(request, response) {
const user = new User()
user.username = 'Jenny'
user.password = 'top-secret'
yield user.save()
yield response.ok("Pavel")
}
}
Course
hasMany Post
Post
hasMany Comment
Comment
belongsTo User
Course
manyThrough Comment
now I can get the comments of course, but there is no user
of each comment, I've tried:
with('user')
in comments()
of Course
with('user')
in comments()
of Post
but it doesn't work neither.
Hello,
I'm trying to update an object inside a embedsMany list, but the result does not persist to the database.
Controller:
async update({
request,
response,
instance,
params
}) {
const embedInstance = await instance.emailContents()
.find(params.emailId);
embedInstance.merge(request.all())
var result = await instance.emailContents().save(embedInstance)
return response.apiUpdated(result)
}
Models:
const Model = use('Model')
class EmailContent extends Model {
static get createTimestamp () { return 'createdAt' }
static get updateTimestamp () { return 'updatedAt' }
}
class Campaign extends Model {
user() {
return this.belongsTo('App/Models/User')
}
emailContents() {
return this.embedsMany('App/Models/EmailContent', '_id', 'emailContents')
}
banners() {
return this.embedsMany('App/Models/BannerContent', '_id', 'banners')
}
textMessages() {
return this.embedsMany('App/Models/TextMessageContent', '_id', 'textMessages')
}
}
I have already created the object i want to create but i cannot update it.
Best way I've seen to provide this config would be something like this:
{
connection: 'mongodb',
mongodb: {
client: 'mongodb',
connection: {
host: 'localhost',
options: {
connectTimeoutMS: 15000,
socketTimeoutMS: 180000,
replicaSet: 'myReplicaSet'
}
}
}
}
This way it would be possible to pass through other options (like the above timeouts) specific to the mongo client. Looks like the connection string is the only thing that needs to be tweaked to support this. I'm happy to make a PR if this config is acceptable.
Hey i wrote a hook so i could define field validation for models just before saving just like Django and other frameworks.
My Model has a method that returns an object of indicative (the validation library for adonis) rules.
validationRules() {
const {
rule
} = require('indicative')
return {
password: [
rule('required')
],
email: [
rule('required')
],
}
}
And i have a hook that a add to the beforeSave event
/**
* If the instance does not have set some values, it
* will set the defaul values if set
*
* @method
*
* @param {Object} instance
*
* @return {void}
*/
ValidatedModelHook.validate = async (instance) => {
/* We obtain the default values */
const validationRules = instance.validationRules()
const validation = await validateAll(instance.$attributes, validationRules)
if (validation.fails()) {
throw ValidateErrorException.invoke(validation.messages())
}
}
And i add the hook like this:
static boot() {
super.boot()
this.addHook('beforeSave', 'ValidatedModel.defaults')
this.addHook('beforeSave', 'ValidatedModel.sanitize')
this.addHook('beforeSave', 'ValidatedModel.validate')
}
I think this could be useful to the framework if it could be integrated to the save functions, although it works fine at the hook level. Just hope this can be done and that i can be useful to you.
Branch | Build failing 🚨 |
---|---|
Dependency | chai |
Current Version | 4.0.2 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As chai is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
This release includes one new feature and a few bug fixes.
.property
assertion (#992; @meeber)expectTypes
to access ssfi
flag (#993; @meeber)The new version differs by 16 commits.
df9073c
Merge pull request #998 from v1adko/make-release
cad9933
Merge pull request #1004 from chaijs/code-owners
cf70b11
Create CODEOWNERS
3397dda
Merge pull request #1005 from meeber/skip-failing-tests
11a6f85
test: skip failing .include
tests in IE11
45cb327
[email protected]
2eddd79
Add ES6 collection support to include() (#994)
3c932e2
feat: allow dates for isBelow and isAbove assertions (#990)
3bcb21c
Merge pull request #979 from chaijs/greenkeeper/browserify-14.4.0
5daceab
Merge pull request #988 from samlanning/missing-var
9116bc8
Merge pull request #993 from meeber/refactor-expect-types
351e968
Merge pull request #992 from meeber/property-target-type
e7b2384
refactor: expectTypes
to access ssfi
flag
e6ddf64
fix: check target's type in .property
assertion
7e466af
Add a missing var keyword found by lgtm.com
There are 16 commits in total.
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
The following code doesn't work.
const cart = await Cart.first()
// cart.items[0].amount is 1
cart.items[0].amount++
await cart.save()
// cart.toJSON().amount is 2 but data in mongodb is 1
I am using the create command through a relationship but the reference is always stored as a string and not as an objectId. Then when i try to query those objects i cannot find them, excepto if a manually enter the database and edit them. I can simple create directly from the Related Model but i find really intuitive to create them through the relationship
My Model:
const Model = use('Model')
class Group extends Model {
contacts() {
return this.hasMany('App/Models/Contact')
}
user() {
return this.belongsTo('App/Models/User')
}
static get objectIds() {
return [
this.primaryKey,
'user_id'
]
}
}
My Controller:
async uploadContactsByFile({
request,
response,
auth
}) {
const user = await auth.getUser();
const group = await user.groups().create({
"name":file.clientName,
})
return response.apiCreated(group)
I'm trying to manually set the table name with the method that Lucid has, but it doesn't seem to work here:
static get table () { return 'my_model_renamed' }
I'm using Adonis 3.2
This query should work. but it fails with an assertion error
yield Tour.with(['type']).paginate(request.input('page', 1), 2);
Missing query type: (find, update, etc)
I'm using this attribute for the model to create dateFields:
static get dateFields () {
return ['date']
}
However, it's not saving it correctly in the database.
For example: I'm giving this date:
"2018-01-11T09:52:56.839Z"
And this gets stored in to the database:
"1970-01-01T00:00:00.000Z"
I am using Lucid mongo 1.1.0.
Hello!
In AdItem.js
module.exports = class AdItem extends Model {
static get objectIDs() { return ['_id', 'ad_id'] } // I've tried objectIdFields, it does not work.
}
Type of mongodb.ObjectID The objectId fields will be converted to mongodb.ObjectID before save to db.
But with these code:
let model = await m('AdItem').first()
data.ad_id = '59e1893b08116f32d8fecb05'
await data.save()
ad_id
value in MongoDB instead ObjectID
.await use('Ad').with('items').fetch()
, but it works if I change ad_id
from String to ObjectId('...') of ad_items
collection in MongoDB manually.Can you explain more detail about saving related foreign keys as ObjectId in Lucid Mongo?
Hello
I used mongoose and i try to reply my project to this framework.
But i dont know where can i create my schema with some options with this lib.
Can you give me some examples to create that.
Ty
I have refresh
method like this:
async refresh({request, auth}) {
const {refreshToken} = request.all()
return await auth.generateForRefreshToken(refreshToken)
}
It returns an error:
Cannot read property 'where' of undefined
node_modules/lucid-mongo/src/LucidMongo/Serializers/LucidMongoSerializer.js
token = await this._Token.where({ token, type, is_revoked: false }).first()
// package.json
{
"name": "adonis-app",
"version": "3.2.1",
"main": "server.js",
"scripts": {
"start": "echo \"\\033[31mWARN: 'start' will be depreciated soon. Instead use 'npm run serve'\" && npm run serve",
"dev": "echo \"\\033[31mWARN: 'dev' will be depreciated soon. Instead use 'npm run serve:dev'\" && npm run serve:dev",
"serve:dev": "nodemon --watch app --watch bootstrap --watch config --watch .env -x node server.js",
"serve": "node server.js",
"lint": "standard"
},
"author": "",
"license": "MIT",
"description": "",
"private": true,
"dependencies": {
"adonis-ace": "^3.0.7",
"adonis-auth": "^1.0.5",
"adonis-commands": "^2.1.5",
"adonis-fold": "^3.0.3",
"adonis-framework": "^3.0.10",
"adonis-lucid": "^3.0.14",
"adonis-lucid-mongodb": "^1.0.42",
"adonis-middleware": "^1.0.11",
"adonis-validation-provider": "^3.0.5",
"adonis-websocket": "^1.0.3",
"shortid": "^2.2.8",
"youch": "^2.0.4"
},
"standard": {
"global": [
"use",
"make"
]
},
"autoload": {
"App": "./app"
},
"devDependencies": {
"nodemon": "^1.11.0",
"standard": "^10.0.1"
}
}
// bootstrap/app.js
'use strict'
/*
|--------------------------------------------------------------------------
| Application Providers
|--------------------------------------------------------------------------
|
| Here we configure the providers required to run adonis application. They
| are registered only once and can be used inside any file using `use`
| keyword.
|
*/
const providers = [
'adonis-lucid-mongodb/providers/DatabaseProvider',
'adonis-lucid-mongodb/providers/LucidMongoProvider',
'adonis-lucid-mongodb/providers/FactoryProvider',
'adonis-framework/providers/ConfigProvider',
'adonis-framework/providers/EnvProvider',
'adonis-framework/providers/EventProvider',
'adonis-framework/providers/HelpersProvider',
'adonis-framework/providers/HashProvider',
'adonis-framework/providers/MiddlewareProvider',
'adonis-framework/providers/RequestProvider',
'adonis-framework/providers/ResponseProvider',
'adonis-framework/providers/RouteProvider',
'adonis-framework/providers/ServerProvider',
'adonis-framework/providers/SessionProvider',
'adonis-framework/providers/StaticProvider',
'adonis-framework/providers/ViewProvider',
'adonis-lucid/providers/DatabaseProvider',
'adonis-lucid/providers/LucidProvider',
'adonis-lucid/providers/FactoryProvider',
'adonis-middleware/providers/AppMiddlewareProvider',
'adonis-auth/providers/AuthManagerProvider',
'adonis-websocket/providers/WsProvider',
'adonis-validation-provider/providers/ValidatorProvider'
]
/*
|--------------------------------------------------------------------------
| Ace Providers
|--------------------------------------------------------------------------
|
| Ace providers are specific to ace, and are not registered when starting
| http server. It helps in reducing boot time.
|
*/
const aceProviders = [
'adonis-lucid-mongodb/providers/CommandsProvider',
'adonis-lucid-mongodb/providers/MigrationsProvider',
'adonis-lucid-mongodb/providers/SchemaProvider',
'adonis-lucid-mongodb/providers/SeederProvider',
'adonis-lucid/providers/CommandsProvider',
'adonis-lucid/providers/MigrationsProvider',
'adonis-lucid/providers/SchemaProvider',
'adonis-lucid/providers/SeederProvider',
'adonis-ace/providers/CommandProvider',
'adonis-commands/providers/GeneratorsProvider',
'adonis-commands/providers/HelperCommandsProvider',
'adonis-commands/providers/ReplProvider'
]
/*
|--------------------------------------------------------------------------
| Namespace Aliases
|--------------------------------------------------------------------------
|
| Each provider is registered with a long unique namespace. Here we alias
| them with a short unique name to keep our import statements short and
| sweet.
|
*/
const aliases = {
LucidMongo: 'Adonis/Src/LucidMongo',
Command: 'Adonis/Src/Command',
Config: 'Adonis/Src/Config',
Database: 'Adonis/Src/Database',
Env: 'Adonis/Src/Env',
Event: 'Adonis/Src/Event',
Factory: 'Adonis/Src/Factory',
Hash: 'Adonis/Src/Hash',
Helpers: 'Adonis/Src/Helpers',
Lucid: 'Adonis/Src/Lucid',
Middleware: 'Adonis/Src/Middleware',
Route: 'Adonis/Src/Route',
Schema: 'Adonis/Src/Schema',
View: 'Adonis/Src/View',
Ws: 'Adonis/Addons/Ws',
Validator: 'Adonis/Addons/Validator'
}
/*
|--------------------------------------------------------------------------
| Ace Commands
|--------------------------------------------------------------------------
|
| Ace Commands are also are registered inside the IoC container. Here we
| register with Ace Kernel using their unique namespace.
|
*/
const commands = [
'App/Commands/Greet',
'Adonis/Commands/Auth:Setup',
'Adonis/Commands/Repl',
'Adonis/Commands/Make:Controller',
'Adonis/Commands/Route:List',
'Adonis/Commands/Make:Migration',
'Adonis/Commands/Make:Model',
'Adonis/Commands/Make:View',
'Adonis/Commands/Make:Command',
'Adonis/Commands/Make:Hook',
'Adonis/Commands/Make:Middleware',
'Adonis/Commands/Make:Seed',
'Adonis/Commands/Make:Listener',
'Adonis/Commands/Migration:Run',
'Adonis/Commands/Migration:Rollback',
'Adonis/Commands/Migration:Refresh',
'Adonis/Commands/Migration:Reset',
'Adonis/Commands/DB:Seed',
'Adonis/Commands/Migration:Status',
'Adonis/Commands/Key:Generate'
]
module.exports = { providers, aceProviders, aliases, commands }
// database/migrations/...
'use strict'
const Schema = use('Schema')
class UsersTableSchema extends Schema {
up () {
this.create('users', (table) => {
table.increments()
table.string('username', 32).unique()
table.string('email').unique()
table.string('password')
table.boolean('confirmed').default(false)
table.string('confirm_token')
table.timestamps()
table.softDeletes()
})
}
down () {
this.drop('users')
}
}
module.exports = UsersTableSchema
// model/user.js
'use strict'
const Lucid = use('LucidMongo')
class User extends Lucid {
static boot () {
super.boot()
this.addHook('beforeCreate', 'User.encryptPassword')
}
static get connection () {
return 'mongodb'
}
static get createTimestamp () { return 'createdAt' }
static get updateTimestamp () { return 'updatedAt' }
static get deleteTimestamp () { return 'deletedAt' }
}
module.exports = User
Hey i wrote a hook so i could define default values for models just before saving just like Django and other frameworks.
My Model has a method that returns the default values of the attributes
defaultValues() {
return {
"is_admin": false
}
}
And i have a hook that a add to the beforeSave event
/**
* If the instance does not have set some values, it
* will set the defaul values if set
*
* @method
*
* @param {Object} instance
*
* @return {void}
*/
ValidatedModelHook.defaults = async (instance) => {
/* We obtain the default values */
const defaultValues = instance.defaultValues()
/* We iterate the default values */
for (const key in defaultValues) {
if (defaultValues.hasOwnProperty(key)) {
/* If the value was not set */
if (instance[key] == null) {
/* We obtain the default value */
const value = defaultValues[key];
/* We verify if the value is a function */
const isFunction = value && value.call && value.apply;
/* We set the defaul value, if it is a function we apply it */
instance[key] = isFunction ? await value() : value;
}
}
}
}
And i add the hook like this:
static boot() {
super.boot()
this.addHook('beforeSave', 'ValidatedModel.defaults')
this.addHook('beforeSave', 'ValidatedModel.sanitize')
this.addHook('beforeSave', 'ValidatedModel.validate')
}
I think this could be useful to the framework if it could be integrated to the save functions, although it works fine at the hook level. Just hope this can be done and that i can be useful to you.
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.