Node.js 编写Mongoose插件-plugin()方法?
我对编写mongoose插件以使所有字段都成为必需字段感兴趣。我知道还有其他方法可以做到这一点,但我喜欢自己编写插件的想法 从文档: 但是,当我从模式创建模型并查看属性时,我没有看到plugin()方法:Node.js 编写Mongoose插件-plugin()方法?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我对编写mongoose插件以使所有字段都成为必需字段感兴趣。我知道还有其他方法可以做到这一点,但我喜欢自己编写插件的想法 从文档: 但是,当我从模式创建模型并查看属性时,我没有看到plugin()方法: 在模型上,我没有看到plugin()方法 plugin方法是在Schema类上定义的,您可以在CpuSchema对象上看到它。 在您的Cpu型号上,您可以通过调用 console.log(Cpu.schema.plugin) 从GitHub上的代码: /** * Registers a p
在模型上,我没有看到plugin()方法 plugin方法是在
Schema
类上定义的,您可以在CpuSchema
对象上看到它。
在您的Cpu
型号上,您可以通过调用
console.log(Cpu.schema.plugin)
从GitHub上的代码:
/**
* Registers a plugin for this schema.
*
* @param {Function} plugin callback
* @param {Object} opts
* @see plugins
* @api public
*/
Schema.prototype.plugin = function (fn, opts) {
fn(this, opts);
return this;
};
当您将插件
函数传递给它时,它只会执行该函数并将模式
引用传递给它
one@demo ~/cloudimageshare-monitoring/project $ node /home/one/cloudimageshare-monitoring/project/app/data/models/cpu.js
{ [Function: model]
base:
{ connections: [ [Object] ],
plugins: [],
models: { Cpu: [Circular] },
modelSchemas: { Cpu: [Object] },
options: { pluralization: true } },
modelName: 'Cpu',
model: [Function: model],
db:
{ base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
collections: { cpus: [Object] },
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
{ paths:
{ timeStamp: [Object],
avaiable: [Object],
status: [Object],
metrics: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree:
{ timeStamp: [Object],
avaiable: [Function: Boolean],
status: [Function: String],
metrics: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options:
{ id: true,
noVirtualId: false,
_id: true,
noId: false,
read: null,
shardKey: null,
autoIndex: true,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
_events: {} },
options: undefined,
collection:
{ collection: null,
opts: { bufferCommands: true, capped: false },
name: 'cpus',
conn:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [ [Object] ],
buffer: true } }
console.log(Cpu.schema.plugin)
/**
* Registers a plugin for this schema.
*
* @param {Function} plugin callback
* @param {Object} opts
* @see plugins
* @api public
*/
Schema.prototype.plugin = function (fn, opts) {
fn(this, opts);
return this;
};