猫鼬不会使用简单的find()返回文档中的所有字段

时间:2018-07-02 10:37:36

标签: node.js mongodb express mongoose mongodb-query

我有以下架构:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: {
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }
},{
  collection: 'users',
  timestamps: true
});

以及以下猫鼬代码:

exports.getUsers = (req, res) => {
  User.find((err, users) => {
    if(err)
      return res.status(400).json( { 'users_get_all': 'failure', 'err': err } );
    return res.status(200).json( { 'users_get_all': 'success', 'users': users } );
  });
};

最初,每个用户文档在“模板”字段中都没有任何内容,因为在用户创建帐户后,即可以将模板附加到该帐户。我已经将一些模板ObjectID手动添加到某些用户的“模板”字段中,但是当我运行getUsers()函数时,将返回用户文档,但没有“模板”字段:

{"users_get_all":"success","users":[{"_id":"5b39f9da294d041b58f97cb3","email":"testemail@email.com","password":"password","firstName":"firstName","lastName":"lastName","createdAt":"2018-07-02T10:09:30.400Z","updatedAt":"2018-07-02T10:21:34.579Z","__v":0},{"_id":"5b39ff5723d93c17bc00eabf","email":"testemail2@email.com","password":"password","firstName":"firstName2","lastName":"lastName2","createdAt":"2018-07-02T10:32:55.308Z","updatedAt":"2018-07-02T10:32:55.308Z","__v":0}]}

如果我用Studio 3T之类的东西查看MongoDB,则模板数组中肯定有对象ID,这些对象ID引用了模板集合中的模板。

Screenshot of Studio 3T showing Users collection

您知道为什么不返回“模板”字段吗?

1 个答案:

答案 0 :(得分:2)

如下更新您的架构:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: [{
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }]
},{
  collection: 'users',
  timestamps: true
});

就像在数据库中一样,您在数组中有模板,并且在架构中将其声明为对象。