mongodb - 为什么我的 Getter 函数不能与 Mongoose 一起使用?
问题描述
我对我的模式的价格属性有一个吸气剂。出于某种原因,当我尝试从 MongoDB 数据库中查询文档时,我的 getter 函数不起作用。价格值完全按照我保存在数据库中的方式返回,而不是通过 Math.floor(v) 获得的四舍五入数字。仅供参考,我的二传手在相同的情况下工作正常。任何帮助将非常感激!
const schema = mongoose.Schema({
name: { type: String, required: true, lowercase: true },
isPublished: Boolean,
author: {
type: String,
required: function (v) {
return this.isPublished;
},
uppercase:true,
},
price: {
type: Number,
required: true,
get: function (v) {
return Math.floor(v);
},
},
});
const Documents = mongoose.model("Documents", schema);
async function myQuery(id) {
const result = await Documents.findById(id);
if (!result) return debug("Not found...");
debug(result);
}
myQuery("60348d30e7b9bf3878170955");
解决方案
const schema = mongoose.Schema({
name: { type: String, required: true, lowercase: true },
isPublished: Boolean,
author: {
type: String,
required: function (v) {
return this.isPublished;
},
uppercase: true,
},
price: {
type: Number,
required: true,
get: function (v) {
return Math.floor(v);
},
},
} {
toObject: { getters: true, setters: true },
toJSON: { getters: true, setters: true },
runSettersOnQuery: true
});
将以下配置添加到您的架构中并试一试。
推荐阅读
- ruby-on-rails - RoR MongoID 查找不起作用?
- node.js - 从 API 创建 Ec2 时扩展根卷
- python - 从 parseAction 返回未更改的标记会生成双重嵌套字典
- python - Numpy ndarray:理解切片对象和“:”
- r - 闪亮的仪表板自动触发
- php - 从 php SESSION var 中提取数据
- opengl-es - Android 中对“glReadBuffer”的未定义引用
- database - Python - 无法从数据库中读取最新数据
- syntax - freemarker中两个数字的除法 - 结果不正确
- json - 根据另一个值获取 JSON 数组中的值的最简单方法是什么?