我对 Mongoose 查询感到非常头疼,我对它还很陌生,想知道是否有人可以提出解决方案。
我的图库集合中有以下字段。
状态(“公开”或“受限”值),
限制(“canview”或“cantview”的值),
canview(允许查看图库的用户 ID (ObjectId) 数组)
然后,我根据当前用户 ID 检查字段,以查看哪些项目可以查看。
如何才能选择以下所有项目
a) 所有“status”=“public”的项目
b) 'status' = 'restricted' 的所有项目,其中 'restricted' = 'canview' 并且 'canview' 包含 UserID
我无法使用 $and 和 $or 来执行此操作,因此尝试使用 $where 代替。使用以下全局函数
var existsInArray = function(str,arr) {
// nb: remember we have typeof ObjectID, so lets convert to strings first!
var newarr = arr.toString().split(',');
// now compare..
if(newarr.inArray(str)) {
return true;
}
return false;
};
我本来希望做这样的事情......
exports.listviewable = function(req, res) {
var reqID = req.user.id;
Gallery
.find()
.$where(function () {
return this.status === "public" || ( this.status === "restricted" && this.restriction === "canview" && existsInArray(reqID, this.canview));
})
.sort('-created')
.exec(function(err, galleries) {
if(err) {
return res.status(400).send({message:getErrorMessage(err)})
} else {
res.json(galleries);
}
});
};
但这不起作用 - 看来我无法在 $where 子句中使用全局的existsInArray 函数?
是否可以这样做(这里有类似的未解决问题 how to call external function in mongoose $where and passing this variable ),或者是否有更好的方法用 AND 和 OR 来做到这一点?
最佳答案
嘿,我建议您访问 mongo 文档 - 他们有很多这方面的信息。
一)
Gallery.find({status: 'public'}, function(err, data){
console.log(data)
});
b)
Gallery.find({status: 'restricted', restricted: 'canview', canview: reqID }, function(err, data){
});
或者两者一起排序...
Gallery.find({$or:[
{status: 'public'},
{status: 'restricted', restricted: 'canview', canview: reqID }
]}, {
sort:{created:-1}
}, function(err, data){
console.log(data)
});
关于javascript - 使用 $where 进行复杂的 Mongoose 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332581/