2014-10-30 77 views
0

的ID字段我用這樣​​的代碼創建用戶帳戶:獲取創建的模型

User.create({ 
    email: req.param('email'), 
    password: req.param('password') 
}).exec(function(err, user) { 

    // I want to get the user ID in here... 

}); 

,我要搶在回調函數中新創建的用戶ID。如果我檢查回調函數的user參數爲exec()它沒有ID字段,只有我傳入的字段(emailpassword)和時間戳(createdAtupdatedAt)。

我能想到的唯一方法就是在用戶的電子郵件地址創建完成後再次查找用戶,但這是一個非常糟糕的方式。

如何獲取新創建的用戶的ID?

回答

0

你不應該使用exec。您應該提供回覆作爲第二個參數create

User.create({ 
    email: req.param('email'), 
    password: req.param('password') 
}, function(err, user) { 
    console.log(user.id); 
}); 
0

你的代碼似乎沒問題。你應該從user.id

我的測試得到ID:

$ sails new app 
$ cd app 
$ sails generate api user 
$ sails console 

sails> User.create({email: '[email protected]', password: '1234'}, function(err, user {console.log(user.id); }); // 1