2017-05-03 71 views
0

我試圖更新對象的數組WO任何成功.. 更新語句不工作..節點貓鼬更新在數組的對象不起作用

我可能必須更新表實例陣列並與新valueand然後保存表更新...

const picked = table.meta.permissions.find(obj => obj._id == req.params.permissionId); 
    console.log('picked: %j', picked); // need to update it ! 

//我怎麼能更新與req.body新值此權限對象?

table.save() 
    .then(savedTable => res.json(savedTable)) 
    .catch(e => next(e);); 

我有權限的在「元」字段陣列: 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], 
     ... 
     }, 
     ... 
    ); 

在控制器中,我首先加載所請求的表,並將其追加到REQ對象,然後我執行updatePermission函數,並嘗試使用$ 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); }); 

}

控制檯日誌顯示當前表權限和req.params和req.body

爲什麼update語句沒有反饋

正確運行

感謝

+0

你應該找出到底是什麼造成這500錯誤(通過檢查日誌文件和/或明確記錄錯誤)。 – robertklep

+0

這是我在測試階段的問題之一...我怎樣才能得到Mongoose輸出日誌... 在我的index.js文件中,我添加了: mongoose.set('debug',(collectionName,method,query調試('$ {collectionName}。$ {method}',util.inspect(query,false,20),doc); }); 但我沒有自己的地方打印出來...... – erwin

+0

你應該添加[適當的錯誤處理](http://expressjs.com/en/guide/error-handling.html)到Express。我不確定你的代碼中有什麼'debug'。 – robertklep

回答

0

我找到了解決這個問題的方法,但我不知道它是否是最好的? 我使用一些(),那麼我保存表更新表對象..

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

     table.meta.permissions.some((obj, idx) => { 
     if (obj._id == req.params.permissionId) { 
      table.meta.permissions[idx].permission = req.body; 
      return true; 
     } 
     return false; 
     }); 

     table.save() 
     .then(savedTable => res.json(savedTable)) 
     .catch(e => next(e);); 
    }