2015-03-02 82 views
0

我的MongoDB架構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 
}); 

問題

如何在表單提交中將包含里程變量的對象放入用戶架構內的milesLog數組中。

這裏是我的MongoDB的圖像:

enter image description here

所以經過表單提交我的數據庫應該是這樣的:

{ 
"_id": { 
    "$oid": "54eda3160fb053cc25a9e287" 
}, 
"userInfo": { 
    "region": "Europe - UK", 
    "fullname": "max26" 
}, 
"local": { 
    "password": "$2a$08$xicDozPMtIiImhwUNuV6SO0llxEnHUK3VlzNh6G7OUgbJwfoxTECC", 
    "email": "[email protected]" 
}, 

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

"__v": 0 
    } 

謝謝您的幫助。

問候,

回答

0

<form method="put">是無效的HTML,將像<form>被處理, GET和POST是用於「方法」屬性的唯一允許值。如果你想使用把這樣使用阿賈克斯:

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

});