问题
I have this document:
...
"username" : "torayeff",
"profile" : {
...
"friends" : [
{
"_id" : "aSD4wmMEsFnYLcvmP",
"state" : "active"
},
{
"_id" : "ShFTXxuQLAxWCh4cq",
"state" : "active"
},
{
"_id" : "EQjoKMNBey7WPGamC",
"state" : "new-request"
}
]
...
}
...
This is query for getting only "state" attribute of given user:
Meteor.users.findOne({_id: userId1, 'profile.friends._id': userId2},
{fields: {_id: 0, 'profile.friends.state.$':1} });
In meteor I am receiving this error:
Exception while simulating the effect of invoking 'activateFriendship' Error: Minimongo doesn't support $ operator in projections yet...
How can I rewrite above query without having error in minimongo?
回答1:
Use $elemMatch for finding nested array, and $ in your projection, so query as below :
Meteor.users.findOne({
"_id": userId1,
"profile.friends": {
"$elemMatch": {
"_id": userId2
}
}
}, {
"profile.friends.state.$": 1
})
回答2:
you can do like
EDIT : if you just want to grab the values without keys, use this
Meteor.users.distinct('profile.friends.state', {_id: userId1, 'profile.friends._id': userId2});
For usual cases :
Meteor.users.findOne({_id: userId1, 'profile.friends._id': userId2}).select({ _id: 0, 'profile.friends.state':1 }).exec()
$
project operator not required
来源:https://stackoverflow.com/questions/29968721/minimongo-doesnt-support-operator-in-projections-yet