1

I am using MongoDB with Nodejs and I am trying to find the usertype value of a specific user so I've got this:

var myQuery= { username: req.body.username }, { "usertype": 1 };
 dbo.collection("usercollection").find(myQuery, function(err, obj) { ...

What I need returned is the value of usertype from that specific user but it keeps saying I have a syntax error with : expected.

How can I fix this?

2 Answers 2

2

You have a syntax error since you're trying to define query and projection for find method in one line, try:

var myQuery= { username: req.body.username };
var options = { projection: { usertype: 1 } };
var cursor = dbo.collection("usercollection").find(myQuery, options)
Sign up to request clarification or add additional context in comments.

4 Comments

It's returning 1 on usertype ... it's a string ... I don't expect usertype to be 1 ... I just need to get the value of whatever usertype value is ... I might have not explain myself properly.
If you use node.js driver for Mongo then you need to add projection as a top level property, check my modified answer
Tried it but same issue console.log(obj); returns a lot of crap and no db fields info
@monroe2019 I think the reason is that you're dealing with cursors in node.js driver. You can take a look here stackoverflow.com/questions/25507866/… to check how to work with them
1

I recommends to first perform the find operation to get the cursor and after it extract data from the cursor like below,

var myQuery= { username: req.body.username };
dbo.collection("usercollection").find(myQuery, {  projection: { usertype: 1}  }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
  });

In your case, the above code will work fine.

8 Comments

also, find's 2nd param requires a separate object of projection, please check in the above code!
It's returning 1 on usertype ... it's a string ... I don't expect usertype to be 1 ... I just need to get the value of whatever usertype value is ... I might have not explain myself properly.
remove projection and check whether it is returning the complete user object!
I've tried console.log(obj); and it's returning way too much info back.
and it is also containing the user type?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.