-1

I know that on robomongo if I want to find _id of user where username = test2 I can use

db.getCollection('user').find({},{_id:1},{"username":"test2"})

now, on visual studio code, I want to find value of field "disabled" from user collection where field "username" value equal to variable "tempusername" value. I tried:

    colUser = mongoDb.collection("user");

 var status = colUser.find({},
    { disabled:1},{ username:tempusername},function (err, doc) {
        console.log(doc);
      });

but it shows value of status is "undefined". What is the write code for this?

user1314404
  • 1,203
  • 2
  • 20
  • 44
  • Also see [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). You essenentially have lots of mistakes which you can solve by taking the time and reading the documentation. – Neil Lunn Apr 26 '18 at 03:56
  • can you propose a simple sample answer that you think is correct ? that would be more helpful – user1314404 Apr 26 '18 at 03:59

2 Answers2

1

I think it's something you're looking for.

const url = 'mongodb://localhost:27017'

MongoClient.connect(url, (err, db) => {
 const dbo = db.db('mydb')
 dbo.collection('user').find({disabled:'1',username:tempusername}).toArray((err, doc) => {
    if(err){
        console.log(err)
    }
    console.log(doc)
    db.close()
 })    
})
Chance
  • 786
  • 1
  • 9
  • 19
  • I tried : var status = colUser.find({ username:tempusername},{ _id:0,disabled:1}).toArray((err, doc) => { if(err){ console.log(err); } console.log(doc); }); but it return undefined. I think cannot get value like that but have to assign the value inside the function colUser.find(), am I right ? – user1314404 Apr 26 '18 at 06:37
  • actually I think I have to use findOne instead to get the value. But it will return something like: This is status: n_auth_mongo.js:78 Promise { pending } n_auth_mongo.js:78 [[PromiseStatus]]:"resolved" [[PromiseValue]]:Object disabled:false and here is what I want to get, but I dont know how to get that disabled:false ? – user1314404 Apr 26 '18 at 07:30
  • @user1314404 disabled is a type of collection or a state. I did not understand. – Chance Apr 26 '18 at 15:48
1

I found the answer, basically the way it work is the result will be return inside the function, so I have to put it like this:

   var statusbuffer;


colUser.findOne({ username:tempusername},{ _id:0,disabled:1},function (err, userstatus){    
    // User result only available inside of this function!
    if (err) {
        next("Failed to update records");
    } else {
    console.log("disabled status here:",userstatus.disabled) // => yields your user results
    statusbuffer = userstatus.disabled;
    next();
    }
});

thanks all for your comments!

user1314404
  • 1,203
  • 2
  • 20
  • 44