node.js 编译 Mongoose 后无法覆盖模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19051041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot overwrite model once compiled Mongoose
提问by Anathema.Imbued
Not Sure what I'm doing wrong, here is my check.js
不知道我做错了什么,这是我的 check.js
var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
var user = mongoose.model('users',{
name:String,
email:String,
password:String,
phone:Number,
_enabled:Boolean
});
user.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere })
});
and here is my insert.js
这是我的 insert.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')
var user = mongoose.model('users',{
name:String,
email:String,
password: String,
phone:Number,
_enabled:Boolean
});
var new_user = new user({
name:req.body.name,
email: req.body.email,
password: req.body.password,
phone: req.body.phone,
_enabled:false
});
new_user.save(function(err){
if(err) console.log(err);
});
Whenever I'm trying to run check.js, I'm getting this error
每当我尝试运行 check.js 时,都会收到此错误
Cannot overwrite 'users' model once compiled.
编译后无法覆盖“用户”模型。
I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.
我知道这个错误是由于架构不匹配造成的,但我看不出这是在哪里发生的?我对猫鼬和 nodeJS 很陌生。
Here is what I'm getting from the client interface of my MongoDB:
这是我从 MongoDB 的客户端界面得到的信息:
MongoDB shell version: 2.4.6 connecting to: test
> use event-db
switched to db event-db
> db.users.find()
{ "_id" : ObjectId("52457d8718f83293205aaa95"),
"name" : "MyName",
"email" : "[email protected]",
"password" : "myPassword",
"phone" : 900001123,
"_enable" : true
}
>
回答by jonnie
So Another Reason why You might get this Error is if you use the same model in different files but your requirepath has a different case. For example in my situation I had:
因此,您可能会收到此错误的另一个原因是,如果您在不同的文件中使用相同的模型,但您的require路径大小写不同。例如在我的情况下,我有:
require('./models/User')in one file and then in another file where I needed access to the User model I had require('./models/user').
require('./models/User')在一个文件中,然后在另一个文件中,我需要访问我拥有的用户模型require('./models/user')。
I guess the look up for modules & mongoose is treating it as a different file. Once I made sure the case matched in both it was no longer an issue.
我猜对模块和猫鼬的查找将其视为不同的文件。一旦我确定大小写在两者中匹配,它就不再是问题。
回答by thtsigma
The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.
发生错误是因为您已经定义了架构,然后您又要重新定义架构。通常,您应该做的是将架构实例化一次,然后在需要时让全局对象调用它。
For example:
例如:
user_model.js
用户模型.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name:String,
email:String,
password:String,
phone:Number,
_enabled:Boolean
});
module.exports = mongoose.model('users', userSchema);
check.js
检查.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
User.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere
})
});
insert.js
插入.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
mongoose.connect('mongodb://localhost/event-db');
var new_user = new User({
name:req.body.name
, email: req.body.email
, password: req.body.password
, phone: req.body.phone
, _enabled:false
});
new_user.save(function(err){
if(err) console.log(err);
});
回答by BJ Anderson
I had this issue while unit testing.
我在单元测试时遇到了这个问题。
The first time you call the model creation function, mongoose stores the model under the key you provide (e.g. 'users'). If you call the model creation function with the same key more than once, mongoose won't let you overwrite the existing model.
第一次调用模型创建函数时,mongoose 将模型存储在您提供的键下(例如“用户”)。如果您多次使用相同的键调用模型创建函数,猫鼬不会让您覆盖现有模型。
You can check if the model already exists in mongoose with:
您可以使用以下命令检查模型是否已存在于 mongoose 中:
let users = mongoose.model('users')
This will throw an error if the model does not exist, so you can wrap it in a try/catch in order to either get the model, or create it:
如果模型不存在,这将引发错误,因此您可以将其包装在 try/catch 中,以便获取模型或创建模型:
let users
try {
users = mongoose.model('users')
} catch (error) {
users = mongoose.model('users', <UsersSchema...>)
}
回答by ZephDavies
I had this issue while 'watching' tests. When the tests were edited, the watch re-ran the tests, but they failed due to this very reason.
我在“观看”测试时遇到了这个问题。当测试被编辑时,手表重新运行测试,但由于这个原因他们失败了。
I fixed it by checking if the model exists then use it, else create it.
我通过检查模型是否存在然后使用它来修复它,否则创建它。
import mongoose from 'mongoose';
import user from './schemas/user';
export const User = mongoose.models.User || mongoose.model('User', user);
回答by munyah
I have been experiencing this issue & it was not because of the schema definitions but rather of serverless offline mode - I just managed to resolve it with this:
我一直在遇到这个问题,这不是因为架构定义,而是因为无服务器离线模式 - 我只是设法解决了这个问题:
serverless offline --skipCacheInvalidation
Which is mentioned here https://github.com/dherault/serverless-offline/issues/258
这里提到https://github.com/dherault/serverless-offline/issues/258
Hopefully that helps someone else who is building their project on serverless and running offline mode.
希望这可以帮助在无服务器上构建项目并运行离线模式的其他人。
回答by Julian
If you are using Serverless offline and don't want to use --skipCacheInvalidation, you can very well use:
如果您离线使用 Serverless 并且不想使用--skipCacheInvalidation,则可以很好地使用:
module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);
回答by James Harrington
If you made it here it is possible that you had the same problem i did. My issue was that i was defining another model with the same name. I called my gallery and my file model "File". Darn you copy and paste!
如果你在这里做到了,你可能遇到了和我一样的问题。我的问题是我正在定义另一个具有相同名称的模型。我称我的画廊和我的文件模型为“文件”。该死的你复制和粘贴!
回答by Toufiq
I solved this by adding
我通过添加解决了这个问题
mongoose.models = {}
before the line :
行前:
mongoose.model(<MODEL_NAME>, <MODEL_SCHEMA>)
Hope it solves your problem
希望它能解决你的问题
回答by ip192
This happened to me when I write like this:
当我这样写时,这发生在我身上:
import User from '../myuser/User.js';
However, the true path is '../myUser/User.js'
然而,真正的路径是'../myUser/User.js'
回答by Alpha BA
To Solve this check if the model exists before to do the creation:
要解决此问题,请在创建模型之前检查模型是否存在:
if (!mongoose.models[entityDBName]) {
return mongoose.model(entityDBName, entitySchema);
}
else {
return mongoose.models[entityDBName];
}

