2017-04-11 7 views
1

mongoose 쿼리와 mongodb 쿼리 사이에 캐싱 계층을 구현하기 위해 ES6 클래스 계층 구조를 만들려고했습니다. 나는이 PR을 보았다 https://github.com/Automattic/mongoose/pull/4668 그리고 그것에 근거하여 아래의 코드를 썼다. 방법이 파생 클래스에서 재정의하기 때문에상속 체인이있는 ES6 클래스 인 몽구스 모델

'use strict' 

const mongoose = require('mongoose'); 
mongoose.connect("mongodb://host:port/db", {}); 
mongoose.connection.on('error', console.error.bind(console, 'DB connection failed', arguments)); 
mongoose.connection.once('open', console.log.bind(console, 'Connected to DB')); 

class Base extends mongoose.Model { 
    save() { 
     console.log('Base class save()') 
     return super.save(); 
    } 

    findOne(query){ 
     console.log('Base class find...'); 
     return super.findOne(query); 
    } 
} 

class Derived extends Base{ 
    save(){ 
     console.log('Derived class save()'); 
     super.save(); 
    } 

    static getOne(){ 
     console.log('Derived class Get one'); 
     return this.findOne({}); 
    } 
} 

let usersSchema = new mongoose.Schema({ name: String }) 

usersSchema.loadClass(Derived); 

let User = mongoose.model(Derived, usersSchema, 'users'); 

setTimeout(function(){ 
    User.getOne() 
      .then(user => console.log('Found user...', user)); 

    let newUser = new User(); 
    console.log('newUser instance of Derived ? ', (newUser instanceof Derived)); 
    console.log('newUser instance of Base ? ', (newUser instanceof Base)); 
    newUser.name = 'Tony'; 
    newUser.save() 
       .then(result => console.log('Saved', result)); 
}, 2000); 

, 나는 다시 기본 클래스를 호출하고 내가 전에/쿼리 후 기본 클래스에 추가 로직을 추가 할 수 있습니다 파생 클래스의 메소드에 대한 호출을 기다리고 있었다.

다음은 메서드 호출이 Derived/Base 클래스에 적용되지 않는다는 것을 나타내는 출력입니다.

출력

Connected to DB 
Derived class Get one 
newUser instance of Derived ? true 
newUser instance of Base ? true 
Base class save() 
Found user... { _id: 58ec765f9dd99f049c2a833b, name: 'Tony', __v: 0 } 

내가 저장 메서드를 호출 할 때, 그것은 파생 클래스를 공격하지 않고 내가 클래스를 파생 에서 getOne 정적 메서드를 호출 할 때, 호출이 충돌하지 않습니다 findOne 메서드는 베이스 클래스입니다. 어디서 잘못 가고 있는지 확실하지 않습니다. 아무도 이것에 약간의 빛을 던질 수 있습니까?

+0

가 왜 몽구스 미들웨어를 사용을 놓친! 또한 캐시의 실제 사용은 훌륭합니다. 새로운 데이터를 저장할 때 캐시를 갱신하지 않으면 캐시 된 데이터를 전달합니다. 기존의 몽구스 코드에 많은 코드를 혼합하는 것이 아니라 매우 간단합니다. – Gntem

+0

감사합니다. Mr.Phoenix. 몽구스 미들웨어를 사용하는 생각.하지만 캐시에서 데이터를 가져 오는 경우 찾기 쿼리를 중단 할 수있는 방법을 찾지 못했습니다. next()를 호출하는 대신 미들웨어에서 데이터를 반환하는 방법이 있습니까? 나는 done 옵션도 보았지만, 후크를 저장하는 데만 적용 할 수 있다고 가정합니다. 내 이해가 맞습니까? – Tony

+0

mongoose 모델 찾기를 호출하기 전에 캐시를 검사하거나 미들웨어를 사용하고 쿼리를 중단하기 위해 커스텀 에러'next (err)'를 던질 수 있습니다. – Gntem

답변

2

나는 어제이 문제에 직면했다.

class User extends mongoose.Model { 
    constructor(user) { 
     super(user); 
     this.settings = new UserSettings({userId: this._id}); 
    } 

    async save(callback) { 
     try { 
      await this.settings.save(); 
      return super.save(callback); 
     } 
     catch (error) { 
      throw error; 
     } 
    } 

    //implement only if you want to use create... 
    static async create(obj, callback) { 
     let user = new User(obj); 
     return user.save(callback); 
    } 
} 

난 당신이 이렇게 경쟁 효과를 가지고는 async 키워드를 누락 생각 : 여기

내가 일하고 있어요 코드입니다.

let prt = new Parent({}).save() (문서 다음) : Parent.find({id: prt.id}).populate('child') 대신에 부모를 만들 때 하위 문서 (기본값)를 자동으로 생성하도록이 코드를 만들었습니다.

좀 심하게 문서화 된, 또는 어쩌면 내가 올바른 문서 ...

+0

Saw this late. 비동기 부분을 알고 있으면 좋습니다. 비동기/대기 키워드를 아직 사용할 계획이 아닙니다. 그러나 구현 관점에서 비동기 부분 이외의 위의 방법에서 잘못된 점을 보시겠습니까? – Tony

+0

잘 모르겠지만 파생 save() 함수에서 return 문을 추가해야합니다. – HRK44