0

I am trying to use the following script to query for a document but the returned document still contains the field (password) that I don't want.

const client = await MongoClient.connect(
                      MONGODB_CONNECTION_STRING, 
                      { useUnifiedTopology: true }
                   );
const db = client.db(DB_NAME);    
const collection = db.collection(collectionName);    
const data = await collection
                .find(
                    {
                        _id: someId
                    },
                    {
                        password: 0
                    }
                );

It supposed to work as I have read in the mongodb documentation but I didn't find any documentation on findOne in mongodb for node.js.

1

I think you need to use project(). See the example here - Projections

| improve this answer | |
  • Thank you. I tried that but, it seems, project() doesn't work with findOne() either. If I use find().project.toArray() then it returns an array, which I don't want. I found a solution to my problem; I think, I should mention that as an answer. – picklu Jan 7 at 14:14
0

The solution to my problem is mentioned in another stackoverflow answer to a different question. If I modify the projection as a value of "fields" as below then findOne() works as I expect.

const data = await collection
            .findOne(
                {
                    _id: someId
                },
                {
                    fields: {password: 0}
                }
            );
| improve this answer | |
  • The answer works at the moment but it gives deprecation warning. – picklu Jan 10 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.