问题描述
我的猫鼬模型定义如下:
I have models in mongoose defined as follows:
user.js
module.exports = function() {
var mongoose = require('mongoose');
// Creates a new Mongoose Schema object
var Schema = mongoose.Schema;
// Collection to hold users
var UserSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
},{
versionKey: false
}
);
// Creates the Model for the User Schema
var User = mongoose.model('User', UserSchema);
var getUserById = function(id, callback) {
User.findById(id, callback);
}
var getUserByUsername = function(username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
return {
getUserById: getUserById,
getUserByUsername: getUserByUsername
}
}()
基本上,我将返回用户模型的客户端可以使用的公共接口. IE.我的用户路线获取了模型,可以调用定义的两个公共方法,仅此而已.我这样做是为了从我的路线中提取出我正在使用mongodb/mongoose的事实.我很有可能会在某个时候也与Postgres对话的User模型,或者可能只是切换到Postgres.因此,我不想遍历代码中称为mongoose特定函数的地方方法.
Basically I am returning a public interface that clients of the User model can use. I.E. my routes for users grabs the model and can call the two public methods defined and nothing else. I am doing this to abstract the fact the I am using mongodb/mongoose from my routes. I will very likely have a User model that talks to postgres as well at some point, or may just switch to postgres. As such I don't want to have to look through the code for places in routes methods that called mongoose specific functions.
这是我的问题.在我需要调用模块的代码中的大多数地方
Here is my problem. Most everywhere in the code when I need a module I call
var someUtil = require('./someUtil');
但是,如果我对猫鼬模型执行多次以上操作,则会收到一条错误消息,指出无法对其进行两次定义.
However if I do that more than once for a mongoose model I get an error stating that it cannot be defined twice.
var User = require('./user'); // Cannot put this in more than one file without getting an error.
是否有更好的方法来编码user.js文件,以便我可以为我的User模型提供一个公共接口,但只定义一次Schema,以便我可以对该文件进行多次调用?
Is there a better way to code the user.js file such that I can provide a public interface to my User model but only define the Schema once so that I can call require more than one time on that file?
推荐答案
我也遇到了这个问题.
您可以做的就是将模式定义包装在try catch中
Something you can do is wrap the schema definition in a try catch
将此行var User = mongoose.model('User', UserSchema);
替换为:
var User;
try {
User = mongoose.model('User', UserSchema);
}
catch(e) {
User = mongoose.model('User');
}
不确定它是否是最好的方法,但是它是否可以工作.
Not sure if its the best way but it will work.
这篇关于多次调用猫鼬模型的require的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!