node.js - 如何为所有模式注册 Mongoose 插件?

标签 node.js mongodb mongoose mongoose-schema

我错过了什么? Mongoose 文档说 mongoose.plugin() 为所有模式注册了一个插件。这是行不通的。我可以在每个模式上注册我的插件。

我的插件:

module.exports = function (schema, options) {

    schema.set('toObject',{
        transform: function (doc, ret, options) {
            return {
                test: 'It worked!'
            };
        }
    });
};

我的模式:

var testPlugin = require('test-plugin.js');

var personSchema = mongoose.Schema({

    _id : { type: String, default: $.uuid.init },

    ssn : { type: String, required: true, trim: true },

    first : { type: String, required: true, trim: true },
    middle : { type: String, required: true, trim: true },
    last : { type: String, required: true, trim: true }
});
personSchema.plugin(testPlugin);

var model = mongoose.model('Person', personSchema);

module.exports = model;

不幸的是,上面的代码有效。但是,以下代码不会:

var personSchema = mongoose.Schema({

    _id : { type: String, default: $.uuid.init },

    ssn : { type: String, required: true, trim: true },

    first : { type: String, required: true, trim: true },
    middle : { type: String, required: true, trim: true },
    last : { type: String, required: true, trim: true }
});

var model = mongoose.model('Person', personSchema);

module.exports = model;

我的测试应用:

var testPlugin = require('test-plugin.js');
mongoose.plugin(testPlugin);

mongoose.Promise = global.Promise;
mongoose.connect(config.db);
mongoose.connection.on('error', function (err) {
    if (err) { throw err; }
});
mongoose.connection.once('open', function (err) {
    if (err) { throw err; }

    seeds.doSeed(function(err){
        if (err) { return process.exit(1); }

        models.Person.find({}, function(err, people){
            if (err) { throw err; }

            var person = people[0];
            var oPerson = person.toObject();

            console.log(JSON.stringify(oPerson));
        });
    });
});

我试过将 mongoose.plugin(testPlugin) 移动到整个 app.js 文件中……在连接之后,等等……但什么都没有成功了。

最佳答案

插件可能未在 mongoose.plugin(myMongoosePlugin) 中注册,因为 mongoose 模型是在您全局注册插件之前创建的。

  • 如果你有 expressjs 路由:

确保在你的 app.js (server.js) 中注册 mongoose 插件,然后再注册/创建 expressjs 路由(使用 mongoose 模型来与数据库通信)。

示例:

app.js

const express = require(express);
const mongoose = require('mongoose');
const myMongoosePlugin = require('<Mongoose Plugin file path>');

mongoose.plugin(myMongoosePlugin);

let app = express();

//register expressjs routes
require('<Express routes file path>')(app, express.Router());

// or create expressjs routes
app.post('/person', (req, res, next) => {
    //where someMethod is using person mongoose model
    this.someController.someMethod(someArguments)
        .then((user) => {
            res.json(user);
        }).catch((error) => {
            next(error);
        });
});

// ... Some other code ...
mongoose.connect(<databaseConnectionString>);
app.listen(<Port>);

关于node.js - 如何为所有模式注册 Mongoose 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000295/

相关文章:

javascript - 为什么 Istanbul/tap 代码覆盖在覆盖每个条件路径时报告 switch 语句未覆盖?

javascript - Node js 中的复杂递归

Java JSON POJO 映射

php - 是否可以在同一个 Dockerfile 中包含 PHP + MongoDb + Nginx?

MongoDB 地理相交无法找到大多边形

javascript - 具有独特字段的 mongo 结果不一致

javascript - Nodejs writestream 内存使用情况

javascript - Joi 验证 - 如何根据输入使字段可选

javascript - underscore.js .keys 和 .omit 没有按预期工作

node.js - Mongoose 中间件更新后不起作用