user10730843
user10730843

Reputation:

Need help on how to store a value from a MongoDB field into a variable

I want to get the size of the array in my DB so I can loop through it, so I created a field called Size in my DB. I want to store the value of this field in a variable so I know how many times I need to loop through the array. I am able to print out the whole document, but I cannot single out the Size value.

Here is my DB document:

_id:ObjectId("5c02492d1c9d440000498a9b")
Names:Array
Size:5

Now, this is my code that I am trying to extract the number 5 from the size field.

var cursor = db.collection('Room').find('Size');
cursor.forEach(function (err, num) {
    if(err) {
        return console.log(err);
    }
    console.log(num);
});

This is what console.log(num) prints:

{ _id: 5c02492d1c9d440000498a9b,
  Names:
   [ 'TjAa0wOe5k4',
     'Sz_YPczxzZc',
     'mM5_T-F1Yn4',
     'En6TUJJWwww',
     '5T_CqqjOPDc' ],
  Size: 5 }

Any ideas/help?

For anyone who is wondering, I figured it out. It turns out that turning the result into an array and then calling numArr[0].Size works. Here is the code for anyone curious:

        var length;
    db.collection('Room').find({'Size': Object}).toArray((err, numArr) => {
            if(err) {
                return console.log(err);
            }
            length = numArr[0].Size
            return length;

    });

Upvotes: 0

Views: 782

Answers (1)

tbking
tbking

Reputation: 9056

Update:

OP fixed it by converting the cursor to an array using .toArray() method and then referencing the property like numArr[0].Size.


You can access the Size property like this:

var size = num.Size;

Have you tried it this way?

Upvotes: 1

Related Questions