vendredi 17 avril 2015

How to retrieve specific queried array collections in MongoDB using NodeJS

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 :



  • I'm using Node MongoDB native driver


Thanks in advance :)


Aucun commentaire:

Enregistrer un commentaire