Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mongoose Schema fields options #102

Closed
zabojad opened this issue Jan 19, 2016 · 2 comments
Closed

Mongoose Schema fields options #102

zabojad opened this issue Jan 19, 2016 · 2 comments

Comments

@zabojad
Copy link

zabojad commented Jan 19, 2016

Hi !

Is this kind of Schema declarations supported ?

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true
  },
  password: {
    type: String,
    required: true
  }
});

// Export the Mongoose model
module.exports = mongoose.model('User', UserSchema);

If yes, how can we do this ?

If not how could we add this ? :)

Thanks !

@clemos
Copy link
Owner

clemos commented Jan 19, 2016

Obviously, you can't "directly" you module.exports and such in Haxe.
But you can totally do:

var UserSchema = new js.npm.mongoose.Schema({
  username: {
    type: "String", // strings are usually safer here
    unique: true,
    required: true
  },
  password: {
    type: "String",
    required: true
  }
});
var userModel = js.npm.Mongoose.mongoose.model('User', userSchema);

This is the "untyped", extern-only way of doing it: you won't have type safety when using this model (documents won't be typed automatically as { username : String, password : String }).

There is an alternative way of declaring schemas, using js.npm.mongoose.macro package.
It is shown in this example : https://github.com/clemos/haxe-js-kit/blob/develop/test/MongooseTest.hx
Basically, you use Haxe typedefs to define your schema; the typedef (ie: StuffData) is transformed into a mongoose schema definition by a macro, and the fields are "copied" to the Model definition (ie: StuffModel) to provide type safety.
Regarding unique and required flags, you can add them as metadata in your typedef:

typedef UserData = {
   @:unique @:required var username : String;
   @:unique @:required var password : String;
};

see https://github.com/clemos/haxe-js-kit/blob/develop/util/Mongoose.hx#L435-L485

Let me know if the example is clear enough for you to adapt it to your needs, and if it's what you would expect.

@zabojad
Copy link
Author

zabojad commented Jan 19, 2016

I missed those metadata. Thank you very much, your answer is very clear, it is what I was expecting...

@zabojad zabojad closed this as completed Jan 19, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants