如何在表单提交时使用Mongoose在MongoDB中的数组中放置对象 [英] How to PUT an object in an array in MongoDB using Mongoose on form submission

查看:184
本文介绍了如何在表单提交时使用Mongoose在MongoDB中的数组中放置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mongoDB模式如下:

My mongoDB schema looks like this:

var userSchema = mongoose.Schema({

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

});

我有以下HTML表单:

And I have the following HTML Form:

   <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数组中.

How to PUT an object containing the miles variable into the milesLog array within my user schema on form submission.

这是我的MongoDB的图片:

Here's an image of my MongoDB:

因此,在提交表单后,我的数据库应如下所示:

So after form submission my Database should look like this:

 {
"_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
  }

感谢您的帮助.

此致

推荐答案

<form method="put">是无效的HTML,将被视为<form>, GET和POST是"method"属性的唯一允许值.如果要使用put,请使用像这样的ajax:

<form method="put"> is invalid HTML and will be treated like <form> , GET and POST are the only allowed values for the "method" attribute. if you want to use put use ajax like this :

$.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);
}

});

这篇关于如何在表单提交时使用Mongoose在MongoDB中的数组中放置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆