【问题标题】:Mongoose returns default value when excluded in find猫鼬在查找中排除时返回默认值
【发布时间】:2015-09-25 23:19:26
【问题描述】:

我的用户架构是,

{
  _id: String,
  name: String,
  status: {type: String, "default": "notverified" }
}

在我的猫鼬查询中,我需要从结果中排除 status 字段。

我的模型查询是这样的,

User.find({}, {status: false}, function(err, users) {
   // process the error
   if (err) console.error(err);

   // process the result
   console.log(users);
});

在上面的查询中,我排除了status,但在结果中我得到了具有架构中定义的默认值的文档。即status: "notverified"

尽管这是 Mongoose 的问题,但为了快速修复,我尝试了这里提到的方法 How to exclude some fields from the document

但它不起作用,因为查询返回单个文档,所以 toObject() 可以工作,但我想从没有 toObject() 方法的文档数组中排除。

任何其他可能的工作解决方案(在将其标记为重复之前)?

【问题讨论】:

  • 这很有趣:如果将false 替换为0,它省略status 属性。根据the MongoDB docsfalse0 都应该这样做,所以显然 Mongoose 改变了这些语义。

标签: node.js mongoose


【解决方案1】:

你误用了猫鼬的投影:

User.find({}, {status: 0}, function(err, users) {
  // process the error
  if (err) console.error(err);
  // process the result
  console.log(users);
});

【讨论】:

  • 不,它没有产生预期的输出,这种方法的结果也一样。
  • 奇怪,它对我有用。你可以尝试不同的语法吗? User.find({}).select("-status").exec(yourCallback);
  • 抱歉,仅供参考,在我使用status: 'verified' 找到的查询中,不是空查询。为简单起见,在此处发布空查询
  • 我不明白。只需改为User.find({"status":"verified}).select("-status").exec(yourCallback);
  • 该死,你能尝试在 mongo shell 中进行查询吗?
猜你喜欢
  • 2020-06-13
  • 2021-03-22
  • 2018-03-07
  • 2018-11-28
  • 2019-09-29
  • 2018-12-03
  • 1970-01-01
  • 2019-02-17
  • 2020-02-28
相关资源
最近更新 更多