Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement map function of Mongodb cursor in node.js (node-mondodb-native)

I am trying to implement following MongoDB query in NodeJS

db.tvseries.find({}).map(function(doc){
    var userHasSubscribed = false;

    doc.followers && doc.followers.forEach(function(follower) {
            if(follower.$id == "abc") {
                userHasSubscribed = true;
            }
        });


    var followers = doc.followers && doc.followers.map(function(follower) {
            var followerObj;
            db[follower.$ref].find({
                    "_id" : follower.$id
                }).map(function(userObj) {
                        followerObj = userObj;
                    });
             return followerObj;
        });

    return {
            "id": doc.name,
            "userHasSubscribed": userHasSubscribed,
            "followers": followers || []
        };
})

Following is the db

users collection

{
     "id": ObjectId("abc"),
     "name": "abc_name"
},
{
     "id": ObjectId("def"),
     "name": "def_name"
},
{
     "id": ObjectId("ijk"),
     "name": "ijk_name"
}

tvseries collection

{
     "id": ObjectId("123"),
     "name": "123_name",
     "followers": [
        {
            "$ref": "users",
            "$id": ObjectId("abc"),
        },
        {
            "$ref": "users",
            "$id": ObjectId("def"),
        }
     ]
},
{
     "id": ObjectId("456"),
     "name": "456_name",
     "followers": [
         {
            "$ref": "users",
            "$id": ObjectId("ijk"),
        },
     ]
},
{
     "id": ObjectId("789"),
     "name": "789_name"
}

I am not able to figure out how to execute the above MongoDB query in NodeJS with the help of node-mongodb-native plugin.

I tried the below code but then I get TypeError: undefined is not a function at .map

var collection = db.collection('users');
collection.find({}).map(function(doc) {
   console.log(doc);
});

How to execute .map function in NodeJS?

Thanks in advance

like image 406
Sreedhar M B Avatar asked Jun 12 '26 05:06

Sreedhar M B


2 Answers

I struggled with this for some time. I found that by adding .toArray() after the map function works.

You could even skip map and only add .toArray() to get all the documents fields.

  const accounts = await _db
    .collection('accounts')
    .find()
    .map(v => v._id) // leaving this out gets you all the fields
    .toArray();

  console.log(accounts); // [{_id: xxx}, {_id: xxx} ...]

Please take note that in order for map to work the function used must return something - your example only console.logs without returning a value.


The forEach solution works but I really wanted map to work.

like image 192
bamse Avatar answered Jun 15 '26 04:06

bamse


I know that I'm pretty late but I've arrived here by searching on Google about the same problem. Finally, I wasn't able to use map function to do it, but using forEach did the trick.

An example using ES6 and StandardJS.

  let ids = []
  let PublicationId = ObjectID(id)
  feeds_collection
    .find({PublicationId})
    .project({ _id: 1 })
    .forEach((feed) => {
      ids.push(feed._id)
    }, () => done(ids))
like image 35
midudev Avatar answered Jun 15 '26 04:06

midudev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!