我正在使用Mongoosejs连接MongoDB.
考虑以下设计的架构示例:
var factSchema= new Schema({
facts: { type:[require('./fact')], select:false}
,roles: {type: [String], required: true, index: {unique: false}}
,c: {type: {}, default: {}} //all calculated stuff based on facts
}
Run Code Online (Sandbox Code Playgroud)
其中明确指出,当正常查询'factSchema'时,不会查询实际的'事实'.只有在明确地对"事实"进行选择之后,才能确保包含这些内容.即:
//factModel is a model derived from factSchema
factModel.findOne({_id:input.id})
.select(["facts","roles","c"]).exec(function(err,result){//do something});
Run Code Online (Sandbox Code Playgroud)
这适用于这个微不足道的案例.但是我已经将factSchema(有关如何:https ://groups.google.com/forum/?fromgroups#!searchin/mongoose-orm/INHERIT/mongoose-orm/aeqGRRnpFvg/lbfIA54hiwYJ的信息)分组,我想查询所有字段一个特定的子类,但它只在运行时知道我正在查询哪个子类.换句话说,我无法明确指定我想要返回的字段.
我该怎么做?
一个可能的解决方案似乎是(?)我可以通过执行subclassedSchema.pathswhere subclassedSchema的子类来获取模式的所有已定义字段factSchema.
这有效,但我可以相信这在未来版本中是稳定的吗?有什么更好,更少的hackish方式来解决这个问题?
2.x分支中没有更好的方法.Schema.paths在3.x中没有变化,因此在可预见的将来可以安全地执行此操作.
3.x具有新select语法,允许简单地调用factModel.findOne(..).select('+facts').exec(callback)以实现期望的结果.