Javascript SailsJs 0.10:User.findOne({u id:id})为唯一主键返回null
我有以下用户模型:Javascript SailsJs 0.10:User.findOne({u id:id})为唯一主键返回null,javascript,node.js,mongodb,express,sails.js,Javascript,Node.js,Mongodb,Express,Sails.js,我有以下用户模型: var model = module.exports = { autoPK: false, attributes: { id: { type: 'string', primaryKey: true }, email: { type: 'string', required: true }, hash: { type: 'string',
var model = module.exports = {
autoPK: false,
attributes: {
id: {
type: 'string',
primaryKey: true
},
email: {
type: 'string',
required: true
},
hash: {
type: 'string',
required: true
},
}
}
并对其进行以下查询:
User.findOne({_id: req.param('user_id')}).populate('drafts').then(function(user) {
console.log("USER: " + JSON.stringify(user) + " FOR: " + req.param('user_id'));
res.send(user.drafts, 200);
});
从print语句中,我知道ID“Rfrq8un5f”没有返回任何内容,但是mongodb命令行输出以下内容:
> db.user.find();
{ "email" : "m@m.com", "hash" : "[...]", "createdAt" : ISODate("2014-05-18T16:32:21.023Z"), "updatedAt" : ISODate("2014-05-18T16:32:21.023Z"), "_id" : "9PTIqHxEc" }
发生了什么事?要解决使用mongo适配器的waterline时id:null的问题,必须添加到模型中:
autoPK:false,schema:true
。您需要两者,但仅使用autoPK false或schema true是不够的
这是一个解决该问题的模型示例(用户模型):
嗯,看起来您正在搜索ID为“Rfrq8un5f”的用户。您的数据库包含一个ID为“9PTIqHxEc”的用户。所以…@ScottGress所以。。。我是一个傻瓜,不管发生了什么;)还有几点:1)当使用sails mongo时,
autoPK
没有任何实际意义,2)适配器将自动为您在id
和\u id
之间进行转换。因此,您不需要在模型中显式配置id
属性,您可以查询id
而不是\u id
以获得所需的结果。
module.exports = {
schema: true,
autoPK: false,
attributes: {
name: {
type: 'string',
required: true
},
email: {
type: 'string',
email: true,
required: true,
unique: true
},
password: {
type: 'string',
minLength: 6,
maxLength: 15,
columnName: 'encrypted_password',
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(values, next) {
require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {
if(err) console.log(err);
values.password = encryptedPassword;
next();
});
}
};