juampi92 / adonis-mongoose-model Goto Github PK
View Code? Open in Web Editor NEWMongoose models for Adonis framework.
License: MIT License
Mongoose models for Adonis framework.
License: MIT License
How can I use this hook in my model? this is my config:
// Hooks/UserHook.js
const Hash = use('Hash')
const UserHook = exports = module.exports = {}
UserHook.hashPassword = async (user) => {
user.password = await Hash.make(user.password)
}
// Models/User.js
const BaseModel = use('Model')
const mongooseHidden = require('mongoose-hidden', )({ defaultHidden: { password: true }})
/**
* @class User
*/
class User extends BaseModel {
static boot ({ schema }) {
schema.plugin(mongooseHidden)
this.addHook('beforeCreate', 'UserHook.hashPassword')
}
/**
* User's schema
*/
static get schema () {
return {
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
type: { type:String, enum: ['root', 'dealer'], required: true },
address: { type:String, required: true }
}
}
static get primaryKey () {
return '_id'
}
}
module.exports = User.buildModel('User')
with this my configuration, returns this error, how can I solve it?
TypeError: this._schema[instruction] is not a function
TypeError: this._schema[instruction] is not a function
at Function.addHook (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\adonis-mongoose-model\src\Model\Base.js:44:30)
at Function.boot (C:\Users\Bryann\Desktop\works\formacho\android_app\server\app\Models\User.js:12:10)
at Function.buildModel (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\adonis-mongoose-model\src\Model\Base.js:162:10)
at Object.<anonymous> (C:\Users\Bryann\Desktop\works\formacho\android_app\server\app\Models\User.js:36:23)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Module.require (module.js:568:17)
at require (internal/module.js:11:18)
at requireStack (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\require-stack\src\index.js:44:12)
at Ioc._resolveAutoloadedPath (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\@adonisjs\fold\src\Ioc\index.js:265:20)
at Ioc.make (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\@adonisjs\fold\src\Ioc\index.js:793:40)
at MongooseSerializer.setConfig (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\adonis-mongoose-model\src\Serializers\MongooseSerializer.js:42:23)
at Auth.authenticator (C:\Users\Bryann\Desktop\works\formacho\android_app\server\node_modules\@adonisjs\auth\src\Auth\index.js:113:24)
Hi! Good morning.
I am getting the following error when working with ref.
Schema hasn't been registered for model "User". Use mongoose.model(name, schema)
--
const { ObjectId } = use('mongoose').Schema.Types
leaderId: {
type: ObjectId,
ref: 'User',
required: true,
}
Thank you to help!
Mongo is giving out this error { MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoError: password must be a string]
This is due to the config in the docs being incorrect, the correct one would look like:
mongodb: {
client: 'mongodb',
connectionString: Env.get('DB_CONNECTION_STRING', ''),
connection: {
host: Env.get('DB_HOST', 'localhost'),
port: Env.get('DB_PORT', 27017),
user: Env.get('DB_USER', 'admin'),
pass: Env.get('DB_PASSWORD', ''),
database: Env.get('DB_DATABASE', 'adonis'),
options: {
// All options can be found at http://mongoosejs.com/docs/connections.html
useNewUrlParser: true // stops throwing warning
},
}
}
We need to polish this module for a production environment so I will just fork it and create a pull request with all the things we find when we are done.
Trying to run 'adonis make:mongoose Foo' as per the guide and get the following error.
/node_modules/adonis-mongoose-model/providers/MongooseProvider.js:50
...options
^
ParseError: Unexpected token
In Controller
async index() {
const user = User.findOne({})
console.log(await auth.generate(user))
}
In Model
'use strict'
const BaseModel = use('MongooseModel')
/**
* @class User
*/
class User extends BaseModel {
static boot({ schema }) {
this.addHook('preSave', 'UserHook.hashPassword')
}
static get primaryKey() {
return 'id'
}
/**
* User's schema
*/
static get schema() {
return {
email: {
type: String,
required: true,
unique: true
},
activationKey: {
type: String,
unique: true,
select: false
}
}
}
}
module.exports = User.buildModel('User')
Error Log
E_RUNTIME_ERROR: Primary key value is missing for user > More details: https://err.sh/adonisjs/errors/E_RUNTIME_ERROR
My hooks on save
this.addHook('preSave', async function() {
this.password = await Hash.make(this.password)
})
const { email, password } = request.all()
const user = await User.findOne({
email: email,
confirmed: true
})
const passwordIsCorrect = await Hash.verify(password, user.password)
console.log(passwordIsCorrect)
what might be the reason for this?
Is it possible to use the mongo and a relational bank at the same time?
Is there a way to leave some hidden fields at the time of consultation?
For example, I would like to hide the password field, but I would not want to do this every time in every query.
In the Lucid documentation, there is the hidden () method, which returns the fields to be hidden, is there anything similar that I can use with mongoose?
It looks like buildSchema is supposed to return the schema and create it if it doesn't exist.
However, at the moment, it seems like buildSchema returns the schema only if it already exists, otherwise it creates the schema but returns undefined.
Therefore, adding methods/virtuals/etc. to the schema is unnecessarily complex because it involves calling buildSchema
at least twice (or accessing the "private" property _schema
):
// we need:
this.buildSchema();
const schema = this.buildSchema();
schema.virtual('something').get(.......);
// or:
this.buildSchema();
this._schema.virtual('something').get(.......);
// instead of simply:
const schema = this.buildSchema();
schema.virtual('something').get(.......);
Hello,
I love your module its very helpful.
But i want to have some example about the object in the model.
for example i want to pass some options like usePushEach
How can i do that ??
Thks for your help
I have a problem with .all() is not a function.
Can you help me with that.
I have an endpoint for update user password, but when use Model.updateOne method, hooks is not called.
See my mode boot:
static boot({ schema }) {
this.addHook('preSave', 'UserHook.hashPassword')
this.addHook('preUpdate', 'UserHook.hashPassword')
}
See my hook:
'use strict'
const Hash = use('Hash')
const UserHook = (exports = module.exports = {})
UserHook.hashPassword = async (user) => {
user.password = await Hash.make(user.password)
}
Can you help me?
HI there
Is possible to use mongoose-autopopulate to auto populate the relationships? If not, exist other way to auto populate relationships?
https://adonisjs.com/docs/4.1/authentication#_jwt
I'm trying revokeTokensForUser but it gives me errors
"TypeError: user.primaryKeyValue is not a function at MongooseSerializer.deleteTokens
async logout ({ request, response, auth }) {
const user = await this.User.find(auth.user._id)
await auth.authenticator('jwt').revokeTokensForUser(user)
return response.apiSuccess(user)
}
Maybe there is something I am missing here, but how do we access the ObjectId
type from a model?
It seems inelegant to have to import mongoose on every model such as: const { ObjectId } = use('mongoose').Schema.Types
.
If it's not there (can't seem to see it in the code) we should probably find a way to make this property available from BaseModel
.
Thanks!
I followed the instructions but Instead of making Foo I updated the User Model
Routes
const Route = use('Route')
const User = use('App/Models/User')
Route.get('/', async ({ request }) => {
const user = await User.create({
name: 'test'
})
console.log(user)
return 'test';
})
User Model
// User Model
'use strict'
const BaseModel = use('MongooseModel')
/**
* @class User
*/
class User extends BaseModel {
static boot ({ schema }) { }
/**
* User's schema
*/
static get schema () {
return {
name: 'String'
}
}
}
module.exports = User.buildModel('User')
Going to index route does a long load.
and chrome says
This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Hey!!
I like your provider, it's amazing!
I saw the latest updates and thought why you didn't publish this in the npm package? Do you need any help with your project?
I think this should be removed and added to the documentation to do it manually as you do with the Mongoose alias. I have installed the provider and now I can't use lucidjs Model.
Thank you for this useful provider :)
I have a custom_lists
collection in mongodb and CustomList
model. Model not matching with collection.
jwt: {
serializer: 'mongoose',
scheme: 'jwt',
model: 'App/Models/User',
token: 'App/Models/Token',
uid: 'email',
password: 'password',
expiry: '30d', // Not yet implemented
options: {
secret: Config.get('app.appKey')
}
},
Hi,
I try to authenticate with JWT or API token in web socket.
and I get this error:
“knex: Required configuration option ‘client’ is missing.”
What is mean?
api: {
serializer: 'mongoose',
model: 'App/Models/Player',
scheme: 'api',
uid: 'name',
token: 'App/Models/Token',
options: {
secret: Env.get('APP_KEY')
}
}
I use with adonisjs library
Thank you.
Did you support the populate method of mongoose? if yes, how?
Is it possible to add virtual fields using this package?
schema only returns the fields but I want to add a virtual field and I don't know where to add the function to handle it.
Thank you
After install your package (incredible per signal), i have problem when using adonis make...
because the execution not finish, i wait per long 10 minutes and not have result, but the file is created :(
My hypothesis is that mongodb is also running when using commands.
Your see this problem on yours projects?
Hey, thanks for keeping this up.
Considering using this for a large project but there a few things from the documentation that are not apparent:
Person
, will now have access to the mongoose queries? Say Person.findOne({ 'name.last': 'Ghost' })
. If so that'd be great to have a section on the documentation with a couple of examples.auth.getUser()
helper work?Thanks!
Edit: I can confirm the auth
helpers getUser()
and attemp()
work as intended.
Looks like a wrong query format, it should be:
return this.remove({
uid,
token: { [selector]: tokens },
}).exec()
When attempting authorization using a session, we get the error "Cannot store ObjectID data type to session store". The reason for this is that the user model returned by the serializer contains non-trivial types, in particular ObjectID
(at least for the _id
field).
Note that even toObject
/toJSON
would not fix this (toJSON
just returns something that will be properly converted to JSON even if it's a class instance, but the AdonisJS session store actually checks the types and rejects those objects).
My current solution is to run this on startup, because I wanted to avoid forking your module and keeping it up to date afterwards:
/*
Goal of this file is to prevent the MongooseSerializer from returning "live" Mongoose models which
then fail to be stored in a session because they contain non-trivial types such as ObjectID.
*/
module.exports = () => {
const MongooseSerializer = use('adonis-mongoose-model/src/Serializers/MongooseSerializer')
function wrapWithSanitizer (klass, method) {
const oldMethod = klass.prototype[method]
klass.prototype[method] = async function (...args) {
const result = await oldMethod.call(this, ...args)
return result ? JSON.parse(JSON.stringify(result)) : result
}
}
wrapWithSanitizer(MongooseSerializer, 'findById')
wrapWithSanitizer(MongooseSerializer, 'findByUid')
// Not sure if this is needed also for 'listTokens'?
}
It would be nice if this could be handled in the serializer itself already.
What do you think of Factory integration.
I got a legacy project that uses your lib but the old developer forked your lib and modified it to be able to use multi-tenant. When I try to change to your version it simply breaks. Can you help me ?
fork repo: https://github.com/wendellpalazzo/adonis-mongoose-model
important commit: wendellpalazzo@8cf9930
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed'
I got this error how to fix this?
I'm trying to use virtuals but i'm getting an error:
"Cannot overwrite
User model once compiled."
My model is like:
const BaseModel = use('MongooseModel')
require('./user')
require('./account')
class Membership extends BaseModel {
static boot ({ schema }) {
schema.virtual('user', {
ref: 'User',
localField: 'user_id',
foreignField: '_id',
justOne: true
})
schema.virtual('account', {
ref: 'Account',
localField: 'account_id',
foreignField: '_id',
justOne: true
})
this.addHook('preFind', async function(next){
this.populate('user')
this.populate('account')
next()
})
}
static get schemaOptions() {
return {
toObject: { virtuals: true },
toJSON: { virtuals: true }
}
}
}
module.exports = Membership.buildModel('Membership')
I looked into some solutions online like this and but i'm not sure how I can do that with this adonis integration of mongoose.
how can i attach plugin to model?
https://mongoosejs.com/docs/plugins.html
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.