简体   繁体   English

使用require从并行Mean.js项目加载模型文件时出现猫鼬错误

[英]Mongoose error when loading model files from a parallel Mean.js project by using require

I have a Mean.js project, very basic as I'm just learning my way around this space. 我有一个Mean.js项目,非常基本,因为我只是在学习这个领域的方法。 I created a parallel project in a seperate folder for a few tests, and I'm not using the mean.js framework for this as it's just command line stuff that I'm using to do some experimentation with. 我在一个单独的文件夹中创建了一个并行项目以进行一些测试,并且我没有为此使用mean.js框架,因为它只是命令行内容,我正在使用它们进行一些实验。

When I try to include one of the mongoose model files from the mean.js project I run into problems. 当我尝试包括来自mean.js项目的猫鼬模型文件之一时,我遇到了问题。 using the absolute or relative paths I can load the file(shown by some debug statements in the file that I add) but I cannot use the schema that should be registered once it has been included. 使用绝对路径或相对路径,我可以加载文件(由我添加的文件中的一些调试语句显示),但是一旦包含它,我将无法使用应注册的模式。 If I copy the file to the local project folder and require that copy, it all works fine. 如果我将文件复制到本地项目文件夹并需要该副本,则一切正常。

So, I'm trying to understand if there is some limitation on how require includes data from other folders. 因此,我试图了解在require如何包含来自其他文件夹的数据方面是否存在某些限制。

Examples: 例子:

require('user.server.model.js'); //works
require('./user.server.model.js'); //works
require('./../../site/app/models/user.server.model.js'); //fails
require('../../site/app/models/user.server.model.js'); //fails
require('/home/mean/site/app/models/user.server.model.js'); //fails

The require succeeds, but when I later try to use the model registered in that file, I get errors on the ones that fail. 需求成功了,但是当我稍后尝试使用在该文件中注册的模型时,失败的却出现了错误。

var User = mongoose.model('User'); //fails on the ones that requied the original location
//Error: MongooseError: Schema hasn't been registered for model "User".

I have tried other tools, like rekuire, but no success. 我尝试了其他工具,例如rekuire,但没有成功。 Additionaly I have tried using a symlink and experienced the same failures. 另外,我尝试使用符号链接并遇到相同的失败。 The files are identical according to diff and the fact that I directly copied the file. 根据diff和我直接复制文件的事实,文件是相同的。 This project is not loading any of the express components, and that is fine. 该项目没有加载任何快速组件,这很好。 I have tried to follow the program flow on the express side of things and I see no reason that this should happen(especially when it works with a local copy). 我尝试遵循程序表达方面的程序流程,但我认为没有理由这样做(尤其是当它与本地副本一起使用时)。

I want to bring in my data models for mongoose from my main application, but not bring this code base into that app, anyone see a way to do this? 我想从我的主应用程序中引入猫鼬的数据模型,但不将此代码库引入该应用程序中,有人看到这样做的方法吗?

Edit 编辑

Shortened version of my code that is failing: 我的代码的缩短版本失败了:

var mongoose = require('mongoose');
require(path.resolve('./user.server.model.js'));
var User = mongoose.model('User'); //errors here if I use a require like the failing ones above

And the code in the boilerplate model file: 以及样板模型文件中的代码:

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
        Schema = mongoose.Schema,
        crypto = require('crypto');

/**
 * A Validation function for local strategy properties
 */
var validateLocalStrategyProperty = function(property) {
        return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
 * A Validation function for local strategy password
 */
var validateLocalStrategyPassword = function(password) {
        return (this.provider !== 'local' || (password && password.length > 6));
};

/**
 * User Schema
 */
var UserSchema = new Schema({
        firstName: {
                type: String,
                trim: true,
                default: '',
                validate: [validateLocalStrategyProperty, 'Please fill in your first     name']
        },
        lastName: {
                type: String,
                trim: true,
                default: '',
                validate: [validateLocalStrategyProperty, 'Please fill in your last     name']
        },
        displayName: {
                type: String,
                trim: true
        },
        email: {
                type: String,
                trim: true,
                default: '',
                validate: [validateLocalStrategyProperty, 'Please fill in your email'],
                match: [/.+\@.+\..+/, 'Please fill a valid email address']
        },
        username: {
                type: String,
                unique: true,
                required: 'Please fill in a username',
                trim: true
        },
        password: {
                type: String,
                default: '',
                validate: [validateLocalStrategyPassword, 'Password should be longer']
        },
        salt: {
                type: String
        },
        provider: {
                type: String,
                required: 'Provider is required'
        },
        providerData: {},
        additionalProvidersData: {},
        roles: {
                type: [{
                        type: String,
                        enum: ['user', 'admin']
                }],
                default: ['user']
        },
        updated: {
                type: Date
        },
        created: {
                type: Date,
                default: Date.now
        }
});

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function(next) {
        if (this.password && this.password.length > 6) {
                this.salt = new Buffer(crypto.randomBytes(16).toString('base64'),     'base64');
                this.password = this.hashPassword(this.password);
        }

        next();
});

/**
 * Create instance method for hashing a password
 */
UserSchema.methods.hashPassword = function(password) {
        if (this.salt && password) {
                return crypto.pbkdf2Sync(password, this.salt, 10000,     64).toString('base64');
        } else {
                return password;
        }
};

/**
 * Create instance method for authenticating user
 */
UserSchema.methods.authenticate = function(password) {
        return this.password === this.hashPassword(password);
};

/**
 * Find possible not used username
 */
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
        var _this = this;
        var possibleUsername = username + (suffix || '');

        _this.findOne({
                username: possibleUsername
        }, function(err, user) {
                if (!err) {
                        if (!user) {
                                callback(possibleUsername);
                        } else {
                                return _this.findUniqueUsername(username, (suffix || 0)     + 1, callback);
                        }
                } else {
                        callback(null);
                }
        });
};

mongoose.model('User', UserSchema);

Change the last line to module.exports=mongoose.model('User', UserSchema); 将最后一行更改为module.exports=mongoose.model('User', UserSchema);

Then change var User = mongoose.model('User'); 然后更改var User = mongoose.model('User'); to var User = require('<path to your User file>'); var User = require('<path to your User file>'); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM