Giter Club home page Giter Club logo

adonis-mongoose-model's Introduction

Hi

I'm Juan Pablo Barreto, a Laravel developer @ Studocu πŸ‘‹

  • ⚑️ Check out my website barreto.jp
  • πŸ”¨ I’m currently working on phecks
  • πŸ“« Reach me on Twitter: @juampi_92
  • πŸ“š I like to write on Medium from time to time
  • πŸͺ“ My gists

πŸ“¦ PHP Packages

πŸ“• test-seo: Small library to assert your SEO structure.
πŸ“˜ artisan-cache-debug: An artisan command to debug your redis cache.
πŸ“— api-resources: Manage multiple API versions.
πŸ“™ laravel-query-cache: A simple fluent interface for caching queries.

adonis-mongoose-model's People

Contributors

dependabot[bot] avatar itsyuka avatar juampi92 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

adonis-mongoose-model's Issues

Cannot store ObjectID data type to session store - Serializer should return only trivial types for findById/findByUid

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.

Last updates

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?

Failed to connect to server

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.

Populate

Did you support the populate method of mongoose? if yes, how?

error when authenticate with JWT or API token in web socket

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.

buildSchema does not return schema unless it already exists

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(.......);

Access ObjectId from model

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!

MongoError: Authentication failed

name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed'

I got this error how to fix this?

question: adonis model functionalities

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:

  • I am assuming that a model, say 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.
  • What about JWT authentication? Is it supported? Does the auth.getUser() helper work?
  • What about adonis traits - any support for those?

Thanks!

Edit: I can confirm the auth helpers getUser() and attemp() work as intended.

How do you ref other models?

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.

Hidden fields in Model

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?

Adding virtual fields to schema

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

hook preSave not working on use updateOne

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?

Hash verify always returns false

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?

Schema hasn't been registered for model

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!

...options ^ ParseError: Unexpected token

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

Using User Hook

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)

Primary Key Value Is Missing For User

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

adonis make command in infinite execution

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?

Moongose Options

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

Tried using this at adonis 4.1 but creating data is not working.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.