【问题标题】:I cant push array into a mongoose schema我无法将数组推入猫鼬模式
【发布时间】:2013-10-11 01:25:40
【问题描述】:

这是我的控制器,一个表单将数据发送到这里:

   exports.addrepair = function(req, res, next){
        Person.findById( req.body.id, function (err, Person) {
               Person.update({id: req.body.id},
                                {$pushAll: {
                                       problem: req.body.problem
                                  , solution:    req.body.solution
                                  , date_on:  Date.now()
                                   }}
                ,{upsert:true},function(err){
                    if(err){
                            console.log(err);
                    }else{
                            console.log("Added");
                    }
                })
        })
    }

架构是:

 var Person = new Schema ({
      name: String,
      Repair: [
        problem: String,
        solution: String,
        date_on: Date
      ]
    })

并且不能对 Person 进行任何修复。使用 console.log,我可以看到所有作品,但看不到推送。

【问题讨论】:

    标签: node.js mongodb controller schema mongoose


    【解决方案1】:

    现在这对我有用。谢谢彼得里昂

    Person.findByIdAndUpdate(req.body.id,                           
           { $push: 
             { repair: 
               { problem: req.body.problem
                 , solution: req.body.solution
                 , date_on: Date.now()
               } 
             },
             function(err){ if(err){ 
               console.log(err) 
             } else { 
                console.log('Added')
             }
           });
    

    【讨论】:

      【解决方案2】:
      exports.addrepair = function(req, res, next) {
        //The Person.findById you had here was unnecessary/useless
        Person.findByIdAndUpdate(req.body.id,
          {
            Repair: {
              $push: {
                problem: req.body.problem,
                solution: req.body.solution,
                date_on:  Date.now()
              }
            }
          },
          //You don't want an upsert here
          function(err){
            if(err){
              console.log(err);
            }else{
              console.log("Added");
            }
          }
        )
      }
      

      【讨论】:

      • Thaks,但不起作用,只推送第一次,只创建 de id 不是问题不是解决方案,而不是 de date_on
      • 好吧,让我们谈谈细节。您发布的架构甚至不是有效的 javascript(您可能在 Repair 数组中省略了花括号)。您小心翼翼地发布您实际运行过的逼真的 sn-ps,也许我会进一步帮助您。
      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 2021-02-09
      • 2018-06-20
      • 2019-09-15
      • 2019-10-13
      • 2015-02-12
      • 1970-01-01
      • 2018-11-22
      相关资源
      最近更新 更多