2014-11-15 84 views
1

我想寫一個提交表單並插入到mongodb的玩具程序,但我不斷收到數據庫錯誤。讓我在這裏粘貼相關的代碼,我希望得到一些幫助。Sails.js:不能做POST插入到mongoDB

我使用的版本0.10.5帆和最新的2.6.5蒙戈,和我的我在我的Mac OSX 10.9運行節點:

型號:Employee.js

module.exports = { 

    attributes: { 
        name: { 
          type: "string", 
          required: true 
         }, 
        email: { 
          type: "string", 
          required: true 
         }, 
        password: { 
           type: "string", 
           required: true 
          } 
    }, 
beforeCreate: function(values, next) { 
     next(); 
    } 
}; 

route.js:

module.exports.routes = { 

    '/registeremployee': { 
    controller: 'employee', 
    action: 'register' 
    }, 

    '/listemployees': { 
    controller: 'employee', 
    action: 'list_all' 
    } 
}; 

EmployeeController.js

module.exports = { 

    index: function(req, res) { 
    res.send(200, {title: "employee index page"}); 
    }, 

    list_all: function(req, res) { 

    Employee.find().exec(function(err, employee) { 

     if (err) { 
     res.send(500, {title: 'error retrieving users'}); 
     } else { 
     res.send(200, {'employees': employee}); 
     } 
    }); 
    }, 

    register: function(req, res) { 

    if (req.method == "GET") { 
     res.view({title: "Form for registering employees"}); 
    } else if (req.method == "POST") { 

     var username = req.param("username"); 
     var password = req.param("password"); 
     var email = req.param("email"); 

     console.log("saving the username: " + username); //username printed as 'undefined' 

     Employee.create({username: username, password: password, email: email}).exec(function(error, employee) { 
     if (error) { 
      console.log('error'); 
      res.send(500, {error: "DB error!"}); 
     } else { 
      console.log('error'); 
      res.send(200, employee); 

      console.log("saved employee: " + employee.username); 
     } 
     }); 
    } 

    } 
}; 

最後,register.ejs模板文件:

<a href="/listemployees">List All Users</a> 
<h2>Form - Create a User</h2> 
<form action="/registeremployee" method="POST"> 
    <table> 
    <tr><td>Name</td><td><input type=」text」 name=」username」 required></td></tr> 
    <tr><td>Password</td><td><input type=」password」 name=」password」 required></td></tr> 
    <tr><td>Email</td><td><input type=」email」 name=」email」 required></td></tr> 
    <tr><td></td><td><input type="submit"></td> 
    </table> 
</form> 

它看起來對我來說,形式不提交數據,作爲參數打印爲未定義/空在我的控制器。

我有這個在我的connections.js:

mongo: { 
    adapter: 'sails-mongo', 
    host: 'localhost', 
    port: 27017, 
    user: '', 
    password: '', 
    database: 'sailsApp1' 
    } 
+0

註銷所有的參數,所以你知道你沒有拼寫錯誤或什麼的。的console.log(req.params()) – Meeker

回答

0

只需更換名稱,用戶名,你能夠將數據保存在數據庫中。

module.exports = { 
    attributes: { 
     username: { 
      type: "string", required: true }, 
      email: { type: "string", required: true }, 
      password: { type: "string", required: true } }, 
    beforeCreate: function(values, next) { next(); } };