Mongoose를 컴파일 한 후에는 모델을 덮어 쓸 수 없습니다.
내가 뭘 잘못하고 있는지 확실하지 않습니다. 여기 내 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 })
});
그리고 여기에 내 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);
});
check.js를 실행하려고 할 때마다이 오류가 발생합니다.
컴파일 된 후에는 'users'모델을 덮어 쓸 수 없습니다 .
이 오류는 스키마의 불일치로 인해 발생한다는 것을 이해하지만 어디에서 발생하는지 알 수 없습니다. 저는 mongoose와 nodeJS를 처음 접했습니다.
내 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" : "myemail@me.com",
"password" : "myPassword",
"phone" : 900001123,
"_enable" : true
}
>
이미 스키마가 정의되어 있고 다시 스키마를 정의하기 때문에 오류가 발생합니다. 일반적으로 수행해야하는 작업은 스키마를 한 번 인스턴스화 한 다음 필요할 때 전역 개체가 호출하도록하는 것입니다.
예를 들면 :
user_model.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
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
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);
});
따라서이 오류가 발생할 수있는 또 다른 이유는 다른 파일에서 동일한 모델을 사용하지만 require
경로의 경우가 다른 경우입니다. 예를 들어 내 상황에서 나는 다음을 가졌다.
require('./models/User')
한 파일에서 내가 가지고있는 사용자 모델에 액세스해야하는 다른 파일에서 require('./models/user')
.
나는 모듈과 몽구스를 찾는 것이 그것을 다른 파일로 취급하고 있다고 생각합니다. 케이스가 둘 다 일치하는지 확인한 후에는 더 이상 문제가되지 않았습니다.
단위 테스트 중에이 문제가 발생했습니다.
모델 생성 함수를 처음 호출 할 때 mongoose는 사용자가 제공 한 키 (예 : '사용자') 아래에 모델을 저장합니다. 동일한 키로 모델 생성 함수를 두 번 이상 호출하면 mongoose는 기존 모델을 덮어 쓰지 않습니다.
모델이 이미 몽구스에 있는지 확인할 수 있습니다.
let users = mongoose.model('users')
모델이 없으면 오류가 발생하므로 모델을 가져 오거나 생성하기 위해 try / catch로 래핑 할 수 있습니다.
let users
try {
users = mongoose.model('users')
} catch (error) {
users = mongoose.model('users', <UsersSchema...>)
}
테스트를 '보는'동안이 문제가 발생했습니다. 테스트가 편집되었을 때 시계는 테스트를 다시 실행했지만 바로 이러한 이유로 실패했습니다.
모델이 있는지 확인한 다음 사용하고 그렇지 않으면 생성하여 수정했습니다.
import mongoose from 'mongoose';
import user from './schemas/user';
export const User = mongoose.models.User || mongoose.model('User', user);
이 문제가 발생했습니다. 스키마 정의 때문이 아니라 서버리스 오프라인 모드 때문이었습니다.이 문제를 해결했습니다.
serverless offline --skipCacheInvalidation
여기에 언급되어 있습니다 https://github.com/dherault/serverless-offline/issues/258
서버리스에서 프로젝트를 빌드하고 오프라인 모드를 실행하는 다른 사람에게 도움이되기를 바랍니다.
당신이 여기에서 그것을 만들었다면 당신은 내가했던 것과 같은 문제를 겪었을 가능성이 있습니다. 내 문제는 내가 같은 이름을 가진 다른 모델을 정의 하고 있었다는 것 입니다. 내 갤러리와 파일 모델을 "파일"이라고했습니다. 복사해서 붙여 넣으세요!
서버리스를 오프라인으로 사용 중이고을 사용하지 않으려면 --skipCacheInvalidation
다음을 매우 잘 사용할 수 있습니다.
module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);
이것은 내가 다음과 같이 쓸 때 나에게 일어났습니다.
import User from '../myuser/User.js';
그러나 실제 경로는 '../myUser/User.js'입니다.
나는 이것을 추가하여 해결했습니다.
mongoose.models = {}
줄 앞에 :
mongoose.model(<MODEL_NAME>, <MODEL_SCHEMA>)
문제가 해결되기를 바랍니다.
허용되는 솔루션이 있다는 것을 알고 있지만 현재 솔루션이 모델을 테스트 할 수 있도록 많은 상용구를 생성한다고 생각합니다. 내 솔루션은 기본적으로 모델을 가져 와서 모델이 등록되지 않은 경우 새 모델을 반환하고있는 경우 기존 모델을 반환하는 함수 내부에 배치하는 것입니다.
function getDemo () {
// Create your Schema
const DemoSchema = new mongoose.Schema({
name: String,
email: String
}, {
collection: 'demo'
})
// Check to see if the model has been registered with mongoose
// if it exists return that model
if (mongoose.models && mongoose.models.Demo) return mongoose.models.Demo
// if no current model exists register and return new model
return mongoose.model('Demo', DemoSchema)
}
export const Demo = getDemo()
Opening and closing connections all over the place is frustrating and does not compress well.
This way if I were to require the model two different places or more specifically in my tests I would not get errors and all the correct information is being returned.
This problem might occur if you define 2 different schema's with same Collection name
If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.
export class User extends Typegoose{
@prop
username?:string
password?:string
}
export class newUser extends User{
constructor() {
super();
}
}
export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });
export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });
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];
}
The schema definition should be unique for a collection, it should not be more then one schema for a collection.
is because your schema is already, validate before create new schema.
var mongoose = require('mongoose');
module.exports = function () {
var db = require("../libs/db-connection")();
//schema de mongoose
var Schema = require("mongoose").Schema;
var Task = Schema({
field1: String,
field2: String,
field3: Number,
field4: Boolean,
field5: Date
})
if(mongoose.models && mongoose.models.tasks) return mongoose.models.tasks;
return mongoose.model('tasks', Task);
You can easily solve this by doing
delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
I have a situation where I have to create the model dynamically with each request and because of that I received this error, however, what I used to fix it is using deleteModel method like the following:
var contentType = 'Product'
var contentSchema = new mongoose.Schema(schema, virtuals);
var model = mongoose.model(contentType, contentSchema);
mongoose.deleteModel(contentType);
I hope this could help anybody.
The reason of this issue is:
you given the model name "users" in the line
<<<var user = mongoose.model('users' {>>> in check.js file
and again the same model name you are giving in the insert file
<<< var user = mongoose.model('users',{ >>> in insert.js
This "users" name shouldn't be same when you declare a model that should be different
in a same project.
For all people ending here because of a codebase with a mix of Typegoose and Mongoose :
Create a db connection for each one :
Mongoose :
module.exports = db_mongoose.model("Car", CarSchema);
Typegoose :
db_typegoose.model("Car", CarModel.schema, "cars");
If you are working with expressjs, you may need to move your model definition outside app.get() so it's only called once when the script is instantiated.
참고URL : https://stackoverflow.com/questions/19051041/cannot-overwrite-model-once-compiled-mongoose
'Nice programing' 카테고리의 다른 글
pip 설치 /usr/local/opt/python/bin/python2.7 : 잘못된 인터프리터 : 해당 파일 또는 디렉토리 없음 (0) | 2020.10.17 |
---|---|
신청서 창을 앞으로 가져 오려면 어떻게해야합니까? (0) | 2020.10.17 |
컴퓨터에있는 총 RAM 양은 어떻게 얻습니까? (0) | 2020.10.17 |
WPF : 응용 프로그램의 중앙에 표시 할 대화 상자 위치를 설정하는 방법은 무엇입니까? (0) | 2020.10.17 |
C ++ 11에서 사용되지 않는 매개 변수 (0) | 2020.10.17 |