簡體   English   中英

使用require從並行Mean.js項目加載模型文件時出現貓鼬錯誤

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

我有一個Mean.js項目,非常基本,因為我只是在學習這個領域的方法。 我在一個單獨的文件夾中創建了一個並行項目以進行一些測試,並且我沒有為此使用mean.js框架,因為它只是命令行內容,我正在使用它們進行一些實驗。

當我嘗試包括來自mean.js項目的貓鼬模型文件之一時,我遇到了問題。 使用絕對路徑或相對路徑,我可以加載文件(由我添加的文件中的一些調試語句顯示),但是一旦包含它,我將無法使用應注冊的模式。 如果我將文件復制到本地項目文件夾並需要該副本,則一切正常。

因此,我試圖了解在require如何包含來自其他文件夾的數據方面是否存在某些限制。

例子:

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

需求成功了,但是當我稍后嘗試使用在該文件中注冊的模型時,失敗的卻出現了錯誤。

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

我嘗試了其他工具,例如rekuire,但沒有成功。 另外,我嘗試使用符號鏈接並遇到相同的失敗。 根據diff和我直接復制文件的事實,文件是相同的。 該項目沒有加載任何快速組件,這很好。 我嘗試遵循程序表達方面的程序流程,但我認為沒有理由這樣做(尤其是當它與本地副本一起使用時)。

我想從我的主應用程序中引入貓鼬的數據模型,但不將此代碼庫引入該應用程序中,有人看到這樣做的方法嗎?

編輯

我的代碼的縮短版本失敗了:

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

以及樣板模型文件中的代碼:

'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);

將最后一行更改為module.exports=mongoose.model('User', UserSchema);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM