简体   繁体   中英

How to create singleton resource in feathers with mongoose?

I need a resource that wouldn't be a collection but single item instead. I don't see anything about customizing mongoose service in that way.

You can return anything from your find method, it does not have to be a collection. So to get an object for eg /singleton you can just do something like:

app.use('/singleton', {
  find: function(params) {
    return Promise.resolve({
      test: 'data'
    });
  }
});

This will of course also work via a websocket socket.emit('singleton::find') . For the Mongoose service there are two options:

1) Extending

Extend the service and then call it with a single object like this:

const MongooseService = require('feathers-mongoose').Service;

class SingletonService extends MongooseService {
  find(params) {
    return super.find(params).then(data => data[0]);
  }
}

app.use('/singleton', new SingletonService({
  Model: Todo,
  name: 'todo'
}));

2) Hooks

Potentially even nicer with feathers-hooks , register an after hook that retrieves the singleton item from the collection originally requested:

const hooks = require('feathers-hooks');

app.configure(hooks())
  .use('/singleton', mongooseService('todo', Todo));

app.service('singleton').hooks({
  after: {
    find(hook) {
      const firstItem = hook.result[0];
      hook.result = firstItem;
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM