【问题标题】:findOneAndUpdate Mongoose with Array使用数组 findOneAndUpdate Mongoose
【发布时间】:2018-03-19 02:27:52
【问题描述】:

我使用 Node.JS 作为后端,使用 Angular4 作为前端。

我想使用 findOneAndUpdate 将某行中的 angular 更改为数组

这是我的模特

        subLot: [{
          room: String,
          beforePicture: String,
          afterPicture: String,
          Realisations: [{
                realisationName : String,
                specialtyName : String,
                pu: Number,
                unite: String,
                quantite: Number,
                startDate: Date, // Attribute to Update
                endDate: Date, // Attribute to Update

          }]
        }]

更改将在 "startDate" "endDate" 中:

(let body = req.body.subLot) subLot[x].room == body[x].room && subLot[x].Realisations[y].realisationName == body[x].Realisations[y].realisationName

这是我在 Node.JS 中的函数

var lot = Devis.
    findOneAndUpdate({ "project": req.params.projectId }, { "$set": { "subLot": req.body.subLot } }).
    exec(function (err, lot) {
        if (err) {
            res.status(500).send(err);
            return;
        }
        res.status(200).json({ lot: lot, success: true });

        return;
    })

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您正在做的是更新数组字段。但是您要做的是更新数组字段的一项,subLot 是一个数组,并且您想要更新该数组中的一个值而不是整个数组。

    我猜你可以做的是根据项目 id 获取 devis,然后找到合适的批次进行更新。如以下代码所示。

    Devis.
    findOne({ "project": req.params.projectId }).
      exec(function (err, devis) {
         if (err) {
             res.status(500).send(err);
             return;
         }
         var lottoUpdate = devis.subLot.find(function(l){ //using Array.find
              return l._id === lot._id;
         });
         lottoUpdate = lot; // update reference of found lot object to the lot object posted from angular.
         devis.save(function(err){
           if (err) {
             res.status(500).send(err);
             return;
          }
          res.status(200).json({ lot: lot, success: true }); 
         }); 
         return;
     })
    

    另外我建议你使用 Promise 而不是回调。

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 2020-10-25
      • 2021-08-04
      • 2022-10-13
      • 2021-11-09
      • 2017-08-13
      • 1970-01-01
      • 2020-08-10
      • 2018-08-18
      相关资源
      最近更新 更多