0

I'm working with Node.js and MongoDB, I used this line:db.collection('users').insertOne({"name":"john", "password":"connor"}) to insert a new document, and now I'd like to get the password from it.

I tried with: var users_array = db.collection('users').find({name:"john"},{password:true, _id:false}).toArray() and I get an array that looks like this: [{"password":"connor"}]

Any way to get that value and save it in a string or something similar?

2
  • var pwString = yourArray[0].password Commented Jan 17, 2016 at 18:00
  • Or use findOne() as var password = db.collection('users').findOne({name:"john"},{password:true, _id:false}).password Commented Jan 17, 2016 at 18:01

1 Answer 1

1

There is nothing special about the array returned. You access properties the same way you always do in JavaScript:

var password = result[0].password;

If you use findOne instead of find you will just get the object directly, without the array, so then you can just use:

var password = result.password;

Side note: You should never store passwords in a way where someone (including yourself) could look inside the database and figure out a password. That means no plaintext and no encrypted passwords. They should be hashed with a random salt, and not by a fast hashing algorithm. Use pbkdf2 or bcrypt.

Sign up to request clarification or add additional context in comments.

3 Comments

Ops, sorry, It didn't worked. I tested it on bash and worked but for some reason in Node.js version it just prints "undefined"
@ÉzhorMalkávar Which version, using find or findOne? If you're using findOne then it indicates that there were no results. Are you sure you still have a user named "john"?
MongoDB Shell version 2.4.9. I use findOne: var pass = db.collection('users').findOne({name:"john"},{password:true, _id:false}).password;And yes, I'm sure there is an user named like that, Shell finds the value using the same query (replacing db.collection('users') for db.users )

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.