Wednesday, 3 May 2017

node mongoose updating an Object in Array doesn't work

I am trying to update an Array of objects wo any success...I got a

500 "Internal Server Error"

I have an Array of permissions in a 'meta' field: MODEL

    const Schema = mongoose.Schema;
    const Permission = new Schema({
      permission: {
        role_id: { type: String },
        canWrite: { type: Boolean }
      }
    });
    const TableSchema = new mongoose.Schema({
      meta: {
        name: { type: String, required: true },
        permissions: [Permission],
        ...
      },
      ...
    );

In the controller , I firstly load the requested table and append it to the req object, then I execute the updatePermission function, and try to update the table instance permission with new values using $set

CONTROLLER

    import Table from '../../models/table.model';

    /**
     * Load table  and append to req.
     */
    function load(req, res, next, id) {
      Table.get(id)
        .then((table) => {
          req.table = table;
          return next();
        })
        .catch(e => next(e));
    }

    function updatePermission(req, res, next) {
      const table = req.table;

      console.log('Current table.meta.permissions: %j', table.meta.permissions, '\n');
      console.log('update permission: ', req.params.permissionId, ' with: ', req.body, '\n');

      const query = { 'meta.permissions._id': req.params.permissionId }
      const update = { $set: { 'meta.permissions.$.permission': req.body } };
      const options = { new: true};
      table.update(query, update, options)
        .then(savedTable => res.json(savedTable))
        .catch((e) => { next(e); });

}

The console log displays the current table permissions and the req.params and req.body

Q1: Why the update doesn't run correctly

Q2: after updating, should I have to use select to return the updated table ?

thanks for feedback



via erwin

No comments:

Post a Comment