查询mongoose中的虚拟属性

dan*_*rvt 14 mongoose mongodb node.js

我的mongoose模式中有一个虚拟属性,我想知道我是否可以使用此属性查询我的文档.

var PersonSchema = new Schema({
  number: {type: Number, required: true},
  name: {type: Date, required: true}
});

PersonSchema.virtual('capitalCaseName').get(function () {
  return this.name.toUpperCase();
});
...
Person.find({"capitalCaseName": "DANIEL"}).exec();
...
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 20

不,你不能.Mongoose虚拟属性仅存在于文档的Mongoose模型表示中,而不存在于执行查询的MongoDB本身中.

您需要查询的任何字段必须在模式中定义为非虚拟字段并持久保存到数据库.

  • 如果可能的话,这不是很好吗? (5认同)
  • 是的,另一种解决方案是使用 [$where](https://docs.mongodb.com/manual/reference/operator/query/where/) 或 [$expr](https://docs.mongodb.com /manual/reference/operator/query/expr/),它允许您手动“计算”虚拟属性并创建更自定义的查询。 (5认同)
  • 是否存在替代解决方案? (2认同)
  • 那就太好了,但是想一想。虚拟数据库不存在于真实数据库中。如果 mongoose 可以使用虚拟属性进行查询,那么您将使其计算每个文档(所有文档)的虚拟字段,然后比较结果。对于数据库引擎来说,这将是一件痛苦的事情,并且会大大减慢你的代码速度。 (2认同)