2014-03-05 2 views
0

Javascript에서 Student 클래스를 썼습니다.지도에서 MongoDB Javascript 클래스를 사용 MapReduce 범위

function Student(info) { 
    this.getName(info); 
    this.getAge(info); 
} 

Student.prototype.getName = function(info) { 
    this.name = info.name; 
}; 

Student.prototype.getAge = function(info) { 
    this.age = info.age; 
}; 

이제이 클래스가 mongoDB mapReduce 프레임 워크의지도 함수 내에 있어야합니다. 즉,

var mapFunction = function() { 
    var student = new Student(this); 
    emit(student.name, student.age); 
}; 

이 함수 맵에는이 함수 외부에서 정의 된 Student에 대한 액세스 권한이 없습니다. 따라서 mapReduce의 범위를 통해이 클래스를 전달해야합니다.

var scopeVar = { Student: Student}; 
db.collection.mapReduce(
    mapFunction, 
    { 
    scope: scopeVar, 
    out: { merge: 'testCollection'} 
    } 
); 

그러나,지도 내부에, 우리는 학생 정의한 것으로 나타났다하지만 Student.prototype가 비어 있습니다. db.testCollection, 나는 대체 mapTest을 썼다

var mapTest = function() { 
    emit(Student, Student.prototype); 
}; 

var scopeVar = { Student: Student}; 
db.collection.mapReduce(
    mapTest, 
    { 
    scope: scopeVar, 
    out: { merge: 'testCollection'} 
    } 
); 

을 테스트하려면, 하나가 출력 문서 따라서이

{_id: function Student(info) { 
    this.getName(info); 
    this.getAge(info); 
}, 
value: {} 
} 

처럼 보이는 볼 수 있습니다, 어떻게 든 범위의 프로토 타입을 복사하지 않는 것 같다 그 물체.

도우미 함수를 클래스의 프로토 타입 함수로 정의하려는 경우 mapReduce의 범위를 통해 어떻게 전달할 수 있습니까?

+0

단순한 일을하지 않고지도 기능에 소스를 포함시켜야하는 이유는 무엇입니까? – WiredPrairie

+0

코드를 최대한 빠르고 간단하게 작성하는 것이 좋습니다. 완전한 대상이 필요한가요? – WiredPrairie

+0

나는 그것이 간단하고 쉬운 해결책이라는 데 동의한다. 그러나 이에 대한 이유가 있습니다. 클래스가 여러 프로토 타입 함수로 매우 복잡하면 코드 관리를 위해 클래스를 분리하여 두는 것이 좋습니다. – user3385768

답변

0

MongoDB가 C로 구현되었다는 가정하에 CLI 또는 실행 엔진이 코드를 읽고이를 V8Engine에 제출합니다. 따라서 Prototype의 해석 된 컨텍스트는 CLI에 의해 인식되지 않으므로 V8 엔진에 제출되지 않습니다. 범위 매개 변수는 매개 변수 메커니즘을 향상 시키지만 예상대로 전체 동적 특성을 제공하지는 않습니다. 내부적으로, mongodb은 주어진 범위로 또 다른 함수를 생성해야합니다. 당신이 언급 한 것을 성취하기 위해 나는 다음과 같이 시도 할 것입니다 :

이것은 작동합니다.

var scopeVar = { Student: Student, StudentPrototype: Student.prototype }; 

var mapFunction = function() { 
Student.prototype = StudentPrototype; 
var student = new Student(this); 
    emit(student.name, student.age); 
}; 
+0

고맙습니다 user3385768, 내 예제 코드 편집 – user640554

0

위의 답변은 올바른 접근 방식입니다. 정답은 다음과 같습니다.

var scopeVar = { Student: Student, StudentPrototype: Student.prototype }; 

var mapFunction = function() { 
    Student.prototype = StudentPrototype; 
    var student = new Student(this); 
    emit(student.name, student.age); 
}; 
관련 문제