Reputation: 11842
I am a beginner in node and mongodb. I am trying to log a value from an object returned from a query using mongoose. I can get the value if I run it within a loop but I am trying to get the value without using loop.
Here is my code
That.find({$and: [{"userId" : {"$ne" : ""}},{"userId" : {"$exists" : true}}]}).sort({"_id" : -1}).limit(1).select("userId").exec(function(err, doc)
{
if(err)
{
console.log('User ID ERROR-');
callback({error:err,message:"Error getting max user ID"});
}else {
console.log('User ID-');
console.log(doc);
console.log(typeof(doc));
doc.forEach(function(eachdoc) {
console.log(eachdoc.userId);
});
process.exit();
}
});
Instead of doing
doc.forEach(function(eachdoc) {
console.log(eachdoc.userId);
});
why it is undefined
if I do console.log(doc.userId);
Also is there any way to get rid of _id
from the result.
Any help is highly appreciated.
Upvotes: 0
Views: 459
Reputation: 10111
Add {_id :0}
after query object in find function to remove _id
from the result. doc
is an array you can't access value directly either you have to use loop or doc[0].userId
.
That.find({
$and: [{
"userId": {
"$ne": ""
}
}, {
"userId": {
"$exists": true
}
}]
}, {
_id: 0
}).sort({
"_id": -1
}).limit(1).select("userId")
Upvotes: 2
Reputation: 3845
Answering first question, you can use
console.log(doc[0].userId);
instead of
doc.forEach(function(eachdoc) {
console.log(eachdoc.userId);
});
For the second question please refer How to prevent MongoDB from returning the object ID when finding a document?
Upvotes: 1