programing

오류를 제거하는 방법: "OverwriteModelError: '정의되지 않은' 모델을 컴파일한 후에는 덮어쓸 수 없습니다."?

minimums 2023. 6. 27. 22:03
반응형

오류를 제거하는 방법: "OverwriteModelError: '정의되지 않은' 모델을 컴파일한 후에는 덮어쓸 수 없습니다."?

MongoDB에 있는 컬렉션의 문서를 업데이트하는 일반적인 방법이 있습니까?

다음 코드가 파일 이름 Deleter.js에 있습니다.

module.exports.MongooseDelete = function (schemaObj, ModelObject);
{
  var ModelObj = new mongoose.Model("collectionName",schemaObj);
  ModelObj.remove(ModelObject);
}

그리고 내 메인 파일 app.js에서 다음과 같이 호출합니다.

var ModObj = mongoose.model("schemaName", schemasObj);
var Model_instance = new ModObj();
var deleter = require('Deleter.js');
deleter.MongooseDelete(schemasObj,Model_instance);

다음 오류가 발생합니다.

OverwriteModelError: Cannot overwrite `undefined` model once compiled.
    at Mongoose.model (D:\Projects\MyPrjct\node_modules\mongoose\lib\index.js:4:13)

두 번째 메소드 호출만 받습니다.해결책이 있는 사람이 있으면 알려주시기 바랍니다.

저는 다음과 같은 문제를 해결할 수 있었습니다.

var Admin;

if (mongoose.models.Admin) {
  Admin = mongoose.model('Admin');
} else {
  Admin = mongoose.model('Admin', adminSchema);
}

module.exports = Admin;

내 생각에 당신은 예를 든 것 같아요.mongoose.Model()동일한 스키마에서 두 번.각 모델을 한 번만 생성하고 필요할 때 글로벌 개체를 보유해야 합니다.

디렉터리 아래의 다른 파일에 다른 모델을 선언하는 것으로 가정합니다.$YOURAPP/models/

$YOURAPPDIR/models/
 - index.js
 - A.js
 - B.js

index.js

module.exports = function(includeFile){
    return require('./'+includeFile);
};

A.js

module.exports = mongoose.model('A', ASchema);

B.js

module.exports = mongoose.model('B', BSchema);

당신의 앱에서.js.

APP.models = require('./models');  // a global object

그리고 당신이 필요할 때

// Use A
var A = APP.models('A');
// A.find(.....

// Use B
var B = APP.models('B');
// B.find(.....

저는 모든 것이 참조로 되어 있고 일이 엉망이 될 수 있기 때문에 가능한 한 글로벌을 피하려고 노력합니다.나의 해결책

모델.js

  try {
    if (mongoose.model('collectionName')) return mongoose.model('collectionName');
  } catch(e) {
    if (e.name === 'MissingSchemaError') {
       var schema = new mongoose.Schema({ name: 'abc });
       return mongoose.model('collectionName', schema);
    }
  }

사실 문제는 그것이 아닙니다.mongoose.model()두 번 인스턴스화됩니다.문제는 그것이Schema두 번 이상 인스턴스화되었습니다.예를 들어, 만약 당신이mongoose.model("Model", modelSchema)n번이고 당신은 스키마에 대한 동일한 참조를 사용하고 있습니다. 이것은 몽구스에게 문제가 되지 않을 것입니다.이 문제는 동일한 모델에서 스키마의 다른 참조를 사용할 때 발생합니다.

var schema1 = new mongoose.Schema(...);
mongoose.model("Model", schema1);
mongoose.model("Model", schema2);

이것은 이 오류가 발생하는 상황입니다.

출처를 살펴보면,(mongoose/lib/index.js:360)이것이 수표입니다

if (schema && schema.instanceOfSchema && schema !== this.models[name].schema){
    throw new mongoose.Error.OverwriteModelError(name);
}

글로벌하고 예외적인 취급은 피하는 게 낫다는 걸 알았어요

var mongoose = require("mongoose");
var _ = require("underscore");

var model;
if (_.indexOf(mongoose.modelNames(), "Find")) {
    var CategorySchema = new mongoose.Schema({
        name: String,
        subCategory: [
            {
                categoryCode: String,
                subCategoryName: String,
                code: String
            }
        ]
    }, {
        collection: 'category'
    });
    model = mongoose.model('Category', CategorySchema);
}
else {
    model = mongoose.model('Category');
}


module.exports = model;

이는 두 경로에 하나의 모델이 필요하기 때문입니다.

주석 모델 파일

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var CommentSchema = Schema({
  text: String,
  author: String
})

module.exports = mongoose.model('Comment', CommentSchema)

시드 파일

const commentData = {
  user: "David Lee",
  text: "This is one comment"
}
var Comment = require('./models/Comment')

module.exports = function seedDB () {
  Comment.create(commentData, function (err, comment) {
    console.log(err, commemt)
  })
}

색인 파일

var Comment = require('./models/comment')
var seedDB = require('./seeds')
seedDB()
const comment = {
  text: 'This girl is pretty!',
  author: 'David'
}
Comment.create(, function (err, comment) {
    console.log(err, comment)
 })

이제 당신은 얻을 것입니다.throw new mongoose.Error.OverwriteModelError(name)주석 모형이 두 가지 다른 방법으로 필요하기 때문입니다.시드 파일var Comment = require('./models/Comment')◦인덱스 파일var Comment = require('./models/comment')

내 것은 다음 코드로 해결되었습니다.

  module.exports = mongoose.models.nameOne || mongoose.model('nameOne', PostSchema);

문제 자체는 동일한 이름을 가진 모델을 만드는 것입니다. 첫 번째 인수로 "user"를 전달할 때 우리는 컬렉션의 이름이 아닌 모델의 이름만 정의합니다.

ex:mongoose.model("cadastry", cadastryUserSchema, "users")

ex:mongoose.model(nameModel, SchemaExample, NameQueyCollection)

스크립트 정보 입력name: string, schema?: mongoose.Schema<...> | undefined, collection?: string | undefined

언급URL : https://stackoverflow.com/questions/14641834/how-to-get-rid-of-error-overwritemodelerror-cannot-overwrite-undefined-mode

반응형