猫鼬查询嵌套文档返回空数组
我有以下模式:
var Store = mongoose.model('Store', new Schema({
name: String
}));
var Client = mongoose.model('Cllient', new Schema({
name: String,
store: { type: Schema.ObjectId, ref: 'Store' }
}));
var Order = mongoose.model('Order', new Schema({
number: String,
client: { type: Schema.ObjectId, ref: 'Client' }
}));
我正在尝试编写返回订单详细信息的API的网址处理程序,如下所示:
I'm trying to code the Url handler of the API that returns the order details, which looks like this:
app.get('/api/store/:storeId/order/:orderId', function (...));
我正在Url中传递商店ID,以快速检查登录用户是否对商店具有权限.如果不是,则返回403状态.就是说,我认为这个storeId和orderId足以获取订单的数据,因此我正在尝试对嵌套文档进行查询,但这根本行不通.
I'm passing the store id in the Url to quickly check if the logged user has permissions on the store. If not, it returns a 403 status. That said, I think this storeId and the orderId are enough data to get the order, so I'm trying to do a query on a nested document, but it just doesn't work.
Order.findOne(
{ 'client.store': req.params.storeId, _id: req.params.orderId },
function (err, order) { ... });
但是订单对象为空;
即使执行查找,它也会返回一个空数组:
Even when I perform a find, it returns an empty array:
Order.find(
{ 'client.store': req.params.storeId },
function (err, results) { ... });
我知道我也可以将cliendId传递给Url,并先检查客户端是否属于商店,然后再从客户端检索订单,但是我认为客户端部分是多余的,您是否认为?通过使用这两个字段,我应该能够以安全的方式获得订单.
I know that I could as well pass the cliendId to the Url and check first if the client belongs to the store, and then retrieve the order from the client, but I think the client part is redundant, don't you think? I should be able to get the order in a secure way by using only these two fields.
我在这里做什么错了?
好,我找到了.秘密在于填充的匹配选项.最终代码如下:
Ok, I found it. The secret was in the match option of populate. The final code looks like this:
Order
.findOne({ _id: req.params.orderId })
.populate({ path: 'client', match: { store: req.params.storeId } })
.exec(function (err, order) { ... });