【问题标题】:How to PUT an object in an array in MongoDB using Mongoose on form submission如何在表单提交时使用 Mongoose 将对象放入 MongoDB 的数组中
【发布时间】:2015-05-02 22:18:43
【问题描述】:

我的 mongoDB 架构如下所示:

var userSchema = mongoose.Schema({

local            : {
    email        : String,
    password     : String,
},
userInfo         : {
    fullname     : String,
    region       : String,
},
milesLog         : []

});

我有以下 HTML 表单:

   <form action="/miles" method="put">
     <div class="form-group">
        <label>Miles</label>
        <input type="text" class="form-control" name="miles">
    </div>
    <button type="submit" class="btn btn-warning btn-lg">Submit</button>
  </form>

我有以下路线:

  app.put('/miles', isLoggedIn, function(req, res) {

        // WHAT TO DO HERE
 });

问题

如何在提交表单时将包含miles 变量的对象放入我的用户架构中的milesLog 数组中。

这是我的 MongoDB 的图片:

所以在表单提交后,我的数据库应该是这样的:

 {
"_id": {
    "$oid": "54eda3160fb053cc25a9e287"
},
"userInfo": {
    "region": "Europe - UK",
    "fullname": "max26"
},
"local": {
    "password": "$2a$08$xicDozPMtIiImhwUNuV6SO0llxEnHUK3VlzNh6G7OUgbJwfoxTECC",
    "email": "max@gmail.com"
},

"milesLog: [
     {"miles": "21"},
     {"miles": "55"}
],

"__v": 0
  }

感谢您的帮助。

问候,

【问题讨论】:

    标签: javascript node.js forms mongodb mongoose


    【解决方案1】:

    &lt;form method="put"&gt; 是无效的 HTML,将被视为 &lt;form&gt; , GET 和 POST 是“方法”属性的唯一允许值。如果你想像这样使用 put 使用 ajax:

    $.ajax({
            url:'/miles',
            type:'PUT',
            data:{ miles : $('.form-control').val() },
            success:function(data){
               console.log('put');
            },
            error:function(err){
               console.log(err);
            }
    });
    
    //and in back-end recieve this value 
    app.put('/miles', isLoggedIn, function(req, res) {
          var userModel = mongoose.model('User',userSchema),
              miles     = req.body.miles; //recive miles send using ajax
          userModel.update({ "userInfo.fullname" : "max26" } ,
    { $push : { 'milesLog' : { 'miles' : miles } } } , function(err , data ) {
     console.log(data);
    }
    
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2021-06-04
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多