5

I read from mongoose documentation that it is possible to create custom schema types to be added to the ones already existing.

As suggested I tried to look into the mongoose-long example: https://github.com/aheckmann/mongoose-long

I need this in an application I am developing in which I have a profile that is a mongoose model. The profile has several fields such as name, surname and so on that are MultiValueField. A MultiValueField is on object with the following structure:

{
    current : <string>
    providers : <Array>
    values : {
         provider1 : value1,
         provider2 : value2
    }
}

The structure above has a list of allowed providers (ordered by priorities) from which the field's value can be retrieved. The current property keeps track of which provider is currently picked to use as value of the field. Finally the object values contains the values for each provider.

I have defined an object in node.js, whose constructor takes the structure above as argument and provides a lot of useful methods to set a new providers, adding values and so on.

Each field of my profile should be initialized with a different list of providers, but I haven't found a way yet to do so.

If I define MultiValueField as an Embedded Schema, I can do so only having each field as Array. Also I cannot initialize every field at the moment a profile is created with the list of providers.

I think the best solution is to define a SchemaType MultiValueFieldType, that has a cast function that returns a MultiValueField object. However, how can I define such a custom schema type? And how can I use custom options when defining it in the schema of the profile?

I already posted a question on mongoose Google group to ask how to create Custom Schema Types: https://groups.google.com/forum/?fromgroups#!topic/mongoose-orm/fCpxtKSXFKc

rewop
  • 91
  • 1
  • 7

1 Answers1

0

I was able to create custom schema types only as arrays too. You will be able to initialize the model, but this aproach has drawbacks:

  • You will have arrays even if you don't need them
  • If you use ParameterSchema on other model, you will need to replicate it

Custom Schema Type Code:

// Location has inputs and outputs, which are Parameters

// file at /models/Location.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ParameterSchema = new Schema({
  name: String,
  type: String,
  value: String,
});

var LocationSchema = new Schema({
    inputs: [ParameterSchema],
    outputs: [ParameterSchema],
});

module.exports = mongoose.model('Location', LocationSchema);

To initialize the model:

// file at /routes/locations.js
var Location = require('../models/Location');

var location = { ... } // javascript object usual initialization

location = new Location(location);
location.save();

When this code runs, it will save the initialized location with its parameters.

I didn't understand all topics of your question(s), but I hope that this answer helps you.