SailsJs 0.10:User.findOne({_ id:id})为唯一主键返回null

时间:2014-05-29 21:13:10

标签: 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',
        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);
});

从印刷声明中,我知道没有为ID和#34; 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" } 

发生了什么?

1 个答案:

答案 0 :(得分:0)

要使用mongo适配器使用水线时解决autoPK: false, schema: true,您必须添加到模型: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(); }); } }; 。你需要两者,对于autoPK false或schema true是不够的。

这是解决该问题的模型示例(用户模型):

{{1}}