2017-03-01 6 views
0

私はfeathersjsを使用してNodejsプロジェクトでmongooseクエリを実行しようとしています。以下はfeathersjsでServiceクラスのクエリmongooseを使用する方法

は私のスキーマモデルであるなど、見つける取得、更新:

'use strict'; 

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

var schema = new mongoose.Schema({ name: 'string', size: 'string' }); 

const messageModel = mongoose.model('message', schema); 

module.exports = messageModel; 

私はこのフォームを使用することができることを知っている:

私は、一般的のようなサービスその他のようなサービスクラスでマングースのクエリを使用したいと思います
app.use('/messages/:id', service(options), function(req, res){ 

    message.find({ name: req.params.id }, function (err, result) { 
    if (err) return err; 
    res.json(result); 
    }) 

    }); 

が、私のためのより良い利用のサービスクラスであり、このようにマングースクエリを使用します。

'use strict'; 

const service = require('feathers-mongoose'); 
const message = require('./message-model'); 
const hooks = require('./hooks'); 

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

class Service { 

    constructor(options) { 
    this.options = options || {}; 
    } 

    find(params) { 

    message.find({}, function (err, result) { 
    if (err) return err; 
    return Promise.resolve([]); 
    }) 

    } 

    get(id, params) { 

    message.find({ name: id }, function (err, result) { 
    if (err) return err; 
    return Promise.resolve([]); 
    }) 

    } 

} 

module.exports = function() { 
    const app = this; 

    const options = { 
    Model: message, 
    paginate: { 
     default: 5, 
     max: 25 
    } 
    }; 

    mongoose.Promise = global.Promise; 
    mongoose.connect('mongodb://localhost:27017/feathers'); 

    app.use('/messages', new Service(options)); 

    // Get our initialize service to that we can bind hooks 
    const messageService = app.service('/messages'); 

    // Set up our before hooks 
    messageService.before(hooks.before); 

    // Set up our after hooks 
    messageService.after(hooks.after); 
}; 

module.exports.service = Service 

何かがうまくいきません。うまくできません。どうしたらいいですか?

答えて

1

コールバックで約束を返しています。代わりに、コールバックを使用する非同期呼び出しはnew Promise((resolve, reject) => {})にラップされなければなりません。 Bluebirdよう

find(params) { 
    return new Promise((resolve, reject) => { 
    message.find({}, function (err, result) { 
    if (err) { 
     return reject(err); 
    } 
    return resolve(result); 
    }); 
    }); 
} 

ツールは、それが簡単に自動的に約束にコールバックベースのAPIを変換することができます。

+0

ありがとうございます!とてもうまく動作します。私はまだ1つの質問があります。オプションが必要な場合は?私はオブジェクトをコンストラクタに向けることを試みますが、メソッドではオプションが定義されていません。例: 'console.log(options)' – SeaDog

+0

あなたは何を意味するのか分かりません。あなたがそれを必要としないなら、 'constructor'(またはそのような他のメソッド)を追加する必要はありません。 – Daff

+0

これは、デフォルトで生成されたfeathersjsをmongodbで生成するサービスが定数 'const options = {Model:model、default:5、etc.} 'であることを意味しています。この定数はこのようにサービスするのです:' app.use('/messages私の場合、私のサービスクラスのコンストラクタに、デフォルトのメソッドと同じものを 'app.use( '/')、service(options)、function(req、res)メッセージ '、新しいサービス(オプション));'しかし、私のコレクションに5つ以上のドキュメントがある場合、それらはすべて表示されます。定数オプションを使用して5つのドキュメントのみを表示するにはどうすればよいですか? – SeaDog

関連する問題