如何在带有feathersjs的Service类中使用查询mongoose

时间:2017-03-01 13:03:09

标签: node.js mongodb rest mongoose feathersjs

我尝试使用feathersjs在我的Nodejs项目中进行mongoose查询。我想在Service类中使用mongoose查询,就像其他常用服务一样:find,get,update等。

以下是我的架构模型:

'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);
  })

  });

但对我来说最好使用Service类并以这种方式使用mongoose查询:

'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 个答案:

答案 0 :(得分:1)

您将在回调中返回承诺。相反,使用回调的异步调用必须包含在new Promise((resolve, reject) => {})

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

Bluebird这样的工具可以更轻松地将基于回调的API自动转换为承诺。