programing

Mongoose를 사용한 다대다 매핑

oldcodes 2023. 5. 24. 22:22
반응형

Mongoose를 사용한 다대다 매핑

제 디자인에는 플래시 카드 스키마와 패키지 스키마가 있습니다.하나의 플래시 카드는 서로 다른 패키지에 속할 수 있으며 패키지에는 서로 다른 플래시 카드가 포함될 수 있습니다.

아래에 my mongoose 스키마 정의의 제거된 버전을 볼 수 있습니다.

// package-schema.js
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var PackageSchema = new Schema({
    id          : ObjectId,
    title       : { type: String, required: true },
    flashcards  : [ FlashcardSchema ]
});

var exports = module.exports = mongoose.model('Package', PackageSchema);

// flashcard-schema.js
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var FlashcardSchema = new Schema({
    id      : ObjectId,
    type        : { type: String, default: '' },
    story       : { type: String, default: '' },
    packages    : [ PackageSchema ]
});

var exports = module.exports = mongoose.model('Flashcard', FlashcardSchema);

위의 설명에서 알 수 있듯이 이 두 스키마 정의는 별도의 파일에 속하며 서로를 참조합니다.

예상대로 PackageSchema가 정의되지 않았다는 예외가 발생했습니다.몽구스와 다대다 관계를 어떻게 매핑할 수 있습니까?

node, mongoDB, mongoose는 처음이지만, 이를 위한 적절한 방법은 다음과 같습니다.

var PackageSchema = new Schema({
    id: ObjectId,
    title: { type: String, required: true },
    flashcards: [ {type : mongoose.Schema.ObjectId, ref : 'Flashcard'} ]
});

var FlashcardSchema = new Schema({
    id: ObjectId,
    type: { type: String, default: '' },
    story: { type: String, default: '' },
    packages: [ {type : mongoose.Schema.ObjectId, ref : 'Package'} ]
});

이렇게 하면 개체 참조만 저장하고 포함된 개체는 저장하지 않습니다.

올바른 방법으로 실행하고 있지만, 문제는 플래시 카드-schema.js에 PackageSchema를 포함해야 하고 그 반대의 경우도 마찬가지라는 것입니다.그렇지 않으면 이 파일들은 사용자가 참조하는 내용을 전혀 알지 못합니다.

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
    PackageSchema = require('./path/to/package-schema.js')

var FlashcardSchema = new Schema({
    id      : ObjectId,
    type        : { type: String, default: '' },
    story       : { type: String, default: '' },
    packages    : [ PackageSchema ]
});

Schema.add() 메서드를 사용하여 전방 참조 문제를 방지할 수 있습니다.

이 (테스트되지 않은) 솔루션은 스키마를 하나의 .js 파일에 저장합니다.

models/index.js

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

// avoid forward referencing
var PackageSchema = new Schema();
var FlashcardSchema = new Schema();

PackageSchema.add({
    id          : ObjectId,
    title       : { type: String, required: true },
    flashcards  : [ FlashcardSchema ]
});

FlashcardSchema.add({
    id      : ObjectId,
    type        : { type: String, default: '' },
    story       : { type: String, default: '' },
    packages    : [ PackageSchema ]
});

// Exports both types
module.exports = {
    Package:   mongoose.model('Package', PackageSchema),
    Flashcard: mongoose.model('Flashcard', FlashcardSchema)
};  

당신은 이것을 관계형 데이터 저장소처럼 너무 많이 생각하고 있습니다.원하는 경우 MySQL(또는 다른 RDBMS)을 사용합니다.

그렇지 않으면 세 번째 스키마를 사용할 수 있지만 각 개체의 ID(가입 없음, 기억)만 사용하므로 별도의 쿼리에서 서로의 항목을 검색해야 합니다.

https://www.npmjs.com/package/mongoose-relationship

##Many-To-Many with Multiple paths

var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    relationship = require("mongoose-relationship");

var ParentSchema = new Schema({
    children:[{ type:Schema.ObjectId, ref:"Child" }]
});
var Parent = mongoose.models("Parent", ParentSchema);

var OtherParentSchema = new Schema({
    children:[{ type:Schema.ObjectId, ref:"Child" }]
});
var OtherParent = mongoose.models("OtherParent", OtherParentSchema);

var ChildSchema = new Schema({
    parents: [{ type:Schema.ObjectId, ref:"Parent", childPath:"children" }]
    otherParents: [{ type:Schema.ObjectId, ref:"OtherParent", childPath:"children" }]
});
ChildSchema.plugin(relationship, { relationshipPathName:['parents', 'otherParents'] });
var Child = mongoose.models("Child", ChildSchema)

var parent = new Parent({});
parent.save();
var otherParent = new OtherParent({});
otherParent.save();

var child = new Child({});
child.parents.push(parent);
child.otherParents.push(otherParent);
child.save() //both parent and otherParent children property will now contain the child's id 
child.remove() 

이것이 순환/순환 의존성의 문제입니다.이것이 nodejs에서 작동하는 방법입니다.자세한 내용은 "CommonJ의 순환 종속성"을 참조하십시오.S"(http://exploringjs.com/es6/ch_modules.html#sec_modules-in-javascript )

//------ a.js ------
var b = require('b');
function foo() {
    b.bar();
}
exports.foo = foo;

//------ b.js ------
var a = require('a'); // (i)
function bar() {
    if (Math.random()) {
        a.foo(); // (ii)
    }
}
exports.bar = bar;

언급URL : https://stackoverflow.com/questions/11117854/many-to-many-mapping-with-mongoose

반응형