Javascript 嵌套mongoose对象的查询属性
我有一个mongoose(4.8.1)模式,名为Javascript 嵌套mongoose对象的查询属性,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个mongoose(4.8.1)模式,名为文件。每个文件都属于一个工作区。每个工作区要么是私有的,要么不是私有的 因此,我希望允许用户通过检查工作区是否是私有的来查看工作区中的文件。我的猫鼬模式是: var File = new mongoose.Schema({ filename: { type: String, required: true }, workspaceId: { type: String, required: true,
文件
。每个文件都属于一个工作区。每个工作区要么是私有的,要么不是私有的
因此,我希望允许用户通过检查工作区是否是私有的来查看工作区中的文件。我的猫鼬模式是:
var File = new mongoose.Schema({
filename: {
type: String,
required: true
},
workspaceId: {
type: String,
required: true,
ref: 'Workspace'
}
});
var Workspace = new mongoose.Schema({
name: {
type: String,
required: true
},
isPrivate: {
type: Boolean,
default: true
},
}))
因此,首先,我获取工作区中的所有文件:
File.find({
workspaceId: workspaceId
})
.exec().then(function(filesDb){
console.log('filesDb are ', filesDb);
}
我的结局是:
[ { __v: 1,
_id: 589afc46012a0d0e7c3f4e55,
filename: 'file-1486552134649.txt',
workspaceId: '589af17765b3bd72213c6fcb'
} ]
这是正确的(工作区中只有一个文件)
工作空间不是私有的,因此我首先填充工作空间ID:
File.find({
workspaceId: workspaceId
})
.populate('workspaceId')
.exec().then(function(filesDb) {
console.log('filesDb are ', filesDb);
})
我正确地得出以下结论:
[ { __v: 1,
_id: 589afc46012a0d0e7c3f4e55,
filename: 'file-1486552134649.txt',
workspaceId:
{ __v: 1,
_id: 589af17765b3bd72213c6fcb,
isPrivate: false,
}
}
]
因此,现在我想确保文件来自非私有的工作区:
File.find({
workspaceId: workspaceId
})
.populate('workspaceId')
.find({
'workspaceId.isPrivate': false
})
.exec().then(function(filesDb) {
console.log('filesDb are ', filesDb);
})
但是filesDb
最终成为一个空数组
我尝试了其他方法,例如将find
更改为:
.find({
workspaceId: {
isPrivate: false
}
})
但无论工作区是否为私有,都会返回文件
那么,如何查询嵌套对象的属性呢?Mongoose不支持按
填充
d字段进行查询。您应该查询所有匹配的文件
s,填充工作区
,然后筛选出引用私有工作区的文件
s。我将为此定义一个静态方法,例如:
File.statics.findPublicInWorkspace = function(workspaceId) {
return this.find({
workspaceId: workspaceId
})
.populate('workspaceId')
.then(function(files) {
return files.filter(function(file) {
return !file.workspaceId.private;
})
})
};
然后
File.findPublicInWorkspace(workspaceId)
.then(function(filesDb) {
console.log('filesDb are ', filesDb);
})
否则,由于要查询只属于一个工作区的文件,可以先查询此工作区。然后,根据其是否为公共文件,分别返回其所有文件或空列表