I've just tried MongoDB & NodeJS and having issue in finding specific array collections using Nodejs.
Here's the the collections I have :
{
"_id": ObjectId("552aa4da6e25e57ebde7ac6f"),
"username": "blablabla",
"email": "xxx@gmail.com",
"password": "Dummy Trip",
"itinerary": [
{
"_id": ObjectId("552c109adb616795044a919e"),
"title": "test-0",
"desc": "test-0-desc"
},
{
"_id": ObjectId("552c10b0db616795044a91a0"),
"title": "test-1",
"desc": "test-1-desc"
},
{
"_id": ObjectId("552c1128db616795044a91a1"),
"title": "test-2",
"desc": "test-2-desc"
}
]
}
So I need to find the array of itinerary that has objecId of "552c109adb616795044a919e"
In MongoDB terminal I use findOne command & positional $ operator and it works as expected, showing only the array I search for.
Command :
db.user.findOne({ "itinerary._id" : ObjectId("552c109adb616795044a919e") }, {"itinerary.$" : 1})
Result :
{
"_id" : ObjectId("552aa4da6e25e57ebde7ac6f"),
"itinerary" : [
{
"_id" : ObjectId("552c109adb616795044a919e"),
"title" : "test-0",
"desc" : "test-0-desc"
}
]}
But why when I tried to implement it in NodeJS, it shows all records instead of the specific array I search.
Here's my NodeJS :
var userCollection = db.get('user'); userCollection.findOne({ "itinerary._id" : new ObjectID("552c109adb616795044a919e") }, {"itinerary.$" : 1},function(e,userDocs){ console.log(userDocs); });
NodeJS Result (Showing all results) :
{ _id: 552aa4da6e25e57ebde7ac6f, username: 'blablabla', email: 'xxx@gmail.com', password: 'Dummy Trip', itinerary: [ { _id: 552c109adb616795044a919e, title: 'test-0', desc: 'test-0-desc' }, { _id: 552c10b0db616795044a91a0, title: 'test-1', desc: 'test-1-desc' }, { _id: 552c1128db616795044a91a1, title: 'test-2', desc: 'test-2-desc' } ] }
Did I miss something here ?
Note :
Thanks in advance :)
I am assuming your itinerary
is an array. then you will have to use $elemMatch
in mongodb.More details on elemMatch .
You can try something like.
var userCollection = db.get('user');
userCollection.findOne({ "itinerary": { $elemMatch: {_id: new ObjectID("552c109adb616795044a919e")}}}, {"itinerary.$" : 1},function(e,userDocs){
console.log(userDocs);
});
Also i think for matching object id you can use mongoose.Types.ObjectId("552c109adb616795044a919e")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.