【问题标题】:Mongoose is not returning all fields in the document using a simple find()Mongoose 没有使用简单的 find() 返回文档中的所有字段
【发布时间】:2018-12-10 13:36:51
【问题描述】:

我有以下架构:

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
});

还有下面的 Mongoose 代码:

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,模板数组中肯定有 ObjectID,它们引用模板集合中的模板。

知道为什么没有返回“模板”字段吗?

【问题讨论】:

  • 在模式中,您将“模板”作为对象,而在数据库中,您有数组。你能发布数据库的JSON吗?
  • 数据类型不匹配是你的问题。
  • 有效吗??
  • 感谢您的回复,您是对的,我现在已经开始工作了,并且说您的回答是正确的。

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


【解决方案1】:

如下更新您的架构:

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
});

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

【讨论】:

  • 啊天哪,几天前我也在另一个 Schema 中这样做了……非常感谢,我的头撞到墙上了。
  • 奇怪的是,执行 findByIdAndUpdate() 的函数没有抛出错误......它是说每当我这样做时 $push 到“模板”数组都是成功的它确实作为数组元素添加到集合的模板字段中。奇怪的。不过谢谢你的帮助!
猜你喜欢
  • 2021-10-19
  • 2021-02-05
  • 2014-02-01
  • 1970-01-01
  • 2020-11-12
  • 2021-02-17
  • 2018-06-17
  • 2019-03-19
  • 1970-01-01
相关资源
最近更新 更多