Reputation:
I have a query like this:
customers.findOne({name:'X','files.author':'c','files.name':'d'},{'files.$':1},function(err,data2){...
My data is like this:
{
name:"X"
files:[
{name:"b"
author:"a"}
{name:"d"
author:"c"}
]
}
Apparently, if I do
This returns files[0]
. I want files[1]
. How can I do this? Should this code already do this, and therefore, my error is elsewhere?
Apparently,
If I do {name:'X','files.name':'d','files.author':'c'}
it'll work.
If I do {name:'X','files.author':'c','files.name':'d'}
it won't.
I also got my schema reversed. I made an edit to reflect this. name
is defined above author
, actually. So I have to query things in the order according to the schema when using Mongoose's findOne
?
Upvotes: 0
Views: 172
Reputation: 311865
When you want to match multiple fields in the same array element, you need to use $elemMatch
instead of listing them separately:
customers.findOne(
{name: 'X', files: {$elemMatch: {author: 'c', name: 'd'}}},
{'files.$':1},
function(err, data2) {...
When listed separately as you currently have it, they can each match different files
array elements.
Upvotes: 1
Reputation:
Apparently, I needed to flip my query and search for things in the order that they are defined in the schema.
Upvotes: 0
Reputation: 193261
Try to use find
instead. It returns cursor so you can use skip
and limit
methods on it:
customers.find({...}).skip(1).limit(1);
Upvotes: 1