I'm trying to write a mongoose schema that for all call to find() or findOne() will pass a certain value in one of its fields. I tried using the 'default' property on the field declaration, but that didn't work for me.
我正在尝试编写一个mongoose模式,对于所有调用find()或findOne()将在其中一个字段中传递某个值。我尝试在字段声明中使用'default'属性,但这对我不起作用。
Here's my schema:
这是我的架构:
var schema = Schema({
created_at: Date,
type: {type: String, default: "alert"},
timestamp: Number,
order: Number,
description: String,
status: String,
});
I would like every call to find() and findOne() to pass the value "alert" in the "type" field.
我希望每次调用find()和findOne()来传递“type”字段中的值“alert”。
Any ideas?
1 个解决方案
#1
1
You could add a simple wrapper method to your model which will be responsible for finding every document with type: "alert"
. Something like this:
您可以向模型添加一个简单的包装器方法,该方法将负责查找类型为“alert”的每个文档。像这样的东西:
var Model = mongoose.model('Model', theSchema);
Model.alerts = function (q, callback) {
q.type = "alert";
this.find(q, callback);
}
Then you could get what you want with Model.alerts({}, callback)
.
然后你可以用Model.alerts({},callback)得到你想要的东西。
#1
1
You could add a simple wrapper method to your model which will be responsible for finding every document with type: "alert"
. Something like this:
您可以向模型添加一个简单的包装器方法,该方法将负责查找类型为“alert”的每个文档。像这样的东西:
var Model = mongoose.model('Model', theSchema);
Model.alerts = function (q, callback) {
q.type = "alert";
this.find(q, callback);
}
Then you could get what you want with Model.alerts({}, callback)
.
然后你可以用Model.alerts({},callback)得到你想要的东西。