【问题标题】:SailsJs 0.10: User.findOne({_id: id}) returning null for unique primary keySailsJs 0.10:User.findOne({_id: id}) 为唯一主键返回 null
【发布时间】:2014-05-29 21:13:09
【问题描述】:

我有以下用户模型

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“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" } 

发生了什么事?

【问题讨论】:

  • 嗯,您正在搜索 ID 为“Rfrq8un5f”的用户。您的数据库包含一个用户,ID 为“9PTIqHxEc”。所以...
  • @ScottGress 所以...我是个白痴手掌到额头
  • Nawwwwwwwww 它发生了 ;)
  • 其他几点:1) autoPK 在使用sails-mongo 时没有任何实际意义,2) 适配器会自动为您在id_id 之间进行转换.所以你不需要在你的模型中显式配置id属性,你可以查询id而不是_id来得到你想要的结果。

标签: javascript node.js mongodb express sails.js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多