[英]mongoose custom schema types
我從mongoose文檔中讀到,可以創建自定義模式類型以添加到已存在的模式類型中。
正如我所建議的那樣,我試着研究一下mongoose-long的例子: https : //github.com/aheckmann/mongoose-long
我需要在我開發的應用程序中使用它,其中我有一個mongoose模型的配置文件。 該配置文件有多個字段,如name
, surname
等,它們是MultiValueField
。 MultiValueField
位於對象上,具有以下結構:
{
current : <string>
providers : <Array>
values : {
provider1 : value1,
provider2 : value2
}
}
上面的結構有一個允許的提供者列表(按優先級排序),從中可以檢索字段的值。 當前屬性會跟蹤當前選擇哪個提供程序作為字段的值。 最后,對象值包含每個提供程序的值。
我在node.js中定義了一個對象,其構造函數將上面的結構作為參數,並提供了許多有用的方法來設置新的提供者,添加值等等。
我的個人資料的每個字段都應該使用不同的提供者列表進行初始化,但我還沒有找到方法。
如果我將MultiValueField
定義為Embedded Schema
,我只能將每個字段作為Array
。 此外,在使用提供者列表創建配置文件時,我無法初始化每個字段。
我認為最好的解決方案是定義一個SchemaType MultiValueFieldType
,它具有一個返回MultiValueField object
的MultiValueField object
。 但是,如何定義這樣的自定義架構類型? 在配置文件的架構中定義時,如何使用自定義選項?
我已經在mongoose Google網上發布了一個問題,詢問如何創建自定義架構類型: https : //groups.google.com/forum/? fromgroups#! topic / mongoose -orm / fCpxtKSXFKc
我也能夠僅將自定義模式類型創建為數組。 您將能夠初始化模型,但這種方法有缺點:
自定義架構類型代碼:
// 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);
要初始化模型:
// file at /routes/locations.js
var Location = require('../models/Location');
var location = { ... } // javascript object usual initialization
location = new Location(location);
location.save();
當此代碼運行時,它將使用其參數保存初始化位置。
我不明白你問題的所有主題,但我希望這個答案可以幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.