2017-06-07 81 views
0

我正在使用npm向MongoDB中插入數據 - 就像使用表單變量直接注入一樣。這是我可以在瀏覽器中看到我點擊提交按鈕後: FORM DATA用POST請求插入數據到MONGODB

這是我使用插入憑證到數據庫腳本:

request.post(
      'http://127.0.0.1:8081/process_post', { 
       json: { 
        fname: 'john', 
       surname:'smtith', 
       age:100, 
       password: '123as', 
       email: '[email protected]', 
       phone: 9283746, 
       city: 'anywhere', 
       country: 'AZSW', 
       postal_code: 117058, 
       picture: 'something.jpg', 
       description:'description' 
      }, 
      function (error, response, body) { 
       if (!error && response.statusCode == 200) { 
        console.log(body) 
       } 
      } 
     ); 

此服務器端功能:

app.post('/process_post', urlencodedParser, function (req, res) { 
    var response = {fname: req.body.fname, surname: req.body.surname, age: req.body.age, 
password: req.body.password,email: req.body.email, phone: req.body.phone, 
city: req.body.city, country: req.body.country, postal_code: req.body.postal_code, 
description: req.body.description, picture:req.body.picture}; 

//etc 

問題是服務器將所有變量搞亂了,並且對發送的數據進行隨機匹配。另外,在mongo shell中,我可以看到數據是「undefined」...是因爲我發送了一個Json,而服務器端設置爲捕獲變量?

編輯:這些都是服務器

+1

「服務器弄亂了所有的變量」,舉例?以及你如何將數據插入到mongo –

+0

Mongoose不適合你嗎? 'new Model.save()'? –

+0

好吧,我試過了,但還沒有設法使它工作,這個包似乎也更簡單 – Mellville

回答

0

先做請求主體的JSON解析的logs

let reqBody = JSON.parse(req.body) 

下創建自己的數據模型,例如,用戶:

newUser = new User({ 
    'attr1': reqBody.attr1, 
    'attr2': reqBody.attr2, 
    'attrN': reqBody.attrN 
}); 

newUser.save(function storeUser(err, user) { 
    //TODO: check if the user was saved correctly. 
}); 
+0

這個建議在「客戶端」方面,對吧? – Mellville

+0

這是在服務器端 –

+0

好吧,我會試一試 – Mellville