2017-10-09 38 views
0

我正在爲更新調用而苦苦掙扎,因爲某些原因,這似乎不起作用。對於一些快速的上下文,我們有一個Node.js應用程序在帶有Waterline ORM的Sails.js上運行。在使用水線時,無法將項目推入文檔中的MongoDB陣列

按我的package.json文件,這裏是我使用的版本:

  • 連接 - 蒙戈:^ 1.3.2
  • 的MongoDB:^ 2.2.29
  • 帆:0.12〜 0.4
  • 帆 - 蒙戈:^ 0.12.3

我稱之爲集合「產品」,每一款產品看起來像這樣在數據庫:

{ 
    "_id" : ObjectId("59d5f12025423dc0261c911d"), 
    "category" : ObjectId("59a9bcf984d756998eaa22e5"), 
    "status" : "pendingReview", 
    "isDeleted" : false, 
    "events" : [ 
     { 
      "when" : 1507193120, 
      "actor" : "56cc0f76e1a25cde0d2c15ab", 
      "action" : "Submitted product", 
      "note" : "Jeff added this product. It is awaiting review." 
     } 
    ], 
    "productId" : "171005-00000", 
    "createdAt" : ISODate("2017-10-05T08:45:20.538Z"), 
    "updatedAt" : ISODate("2017-10-05T08:45:20.538Z") 
} 

我有一個用戶界面,用戶可以在向網站訪問者顯示多個產品之前「批准」多個產品。爲此,我想更新多個記錄,方法是將status鍵更改爲「批准」,並在每個文檔的events陣列中添加一個事件。該事件必須位於數組的位置0。我試圖更新這些記錄與下面的代碼,但它似乎並沒有工作:

var moment = require('moment'); 
Products.native(function(error, collection) { 

    if (error) { 
     throw error; 
    } 

    collection.update(
     { _id: ['59d5f12025423dc0261c911d'] }, 
     { 
      $set: { 
       status: 'approved', 
       $push: { 
        events: { 
         when: moment().unix(), 
         actor: req.body.userId, 
         action: 'Approved product', 
         note: req.body.userName + ' approved this product.' 
        } 
       } 
      } 
     }, 
     { multi: true }, 
     function(error, count, status) { 

     if (error) { 
      sails.log.error(error); 
      return res.serverError('Database error. Reference ID: ' + req.referenceId); 
     } 

     return res.ok(count); 
    }); 
}); 

當我運行此查詢,我沒有得到任何錯誤,當我檢查我的數據庫,記錄有未更新。我運行查詢時收到以下數據:

{ 
    "ok": 1, 
    "nModified": 0, 
    "n": 0 
} 

這是怎麼回事?爲什麼沒有得到更新?如果我理解正確,查詢能夠找到文檔,但沒有更新。那是對的嗎?如果是的話,我該如何解決這個問題?謝謝。

回答

1

$ push應該與$ set相同。他們都是運營商...

這意味着你應該這樣改變:

{ 
    $set: { 
     status: 'approved' 
    }, 
    $push: { 
     events: { 
      when: moment().unix(), 
      actor: req.body.userId, 
      action: 'Approved product', 
      note: req.body.userName + ' approved this product.' 
     } 
    } 
} 
+0

這是它!謝謝! – Nag