Search code examples
javascriptnode.jsmongodbfeathersjsfeathers-hook

To update single field in a document on MongoDB, what is the best method? update or patch hook in feathersjs


I'm try to update mongodb document in single field, I have doubt to which method i want to use either patch or update using feathers framework, give an example how we can do it.

const { authenticate } = require('feathers-authentication').hooks;

module.exports = {
  before: {
    all: [ authenticate('jwt') ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  after: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};

Solution

  • update will replace the entire document. To merge with existing data patch should be used. This is documented here and here with the following example:

    app.service('messages').patch(1, {
      text: 'A patched message'
    }).then(message => console.log(message));
    
    const params = {
      query: { read: false }
    };
    
    // Mark all unread messages as read
    app.service('messages').patch(null, {
      read: true
    }, params);