简体   繁体   中英

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. 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.

When I try to include one of the mongoose model files from the mean.js project I run into problems. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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