Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js + MongoDB - findOne() return one field not working

Why can I not be able to return only one field using "findOne()"? In the code below, all fields are returned. I also tried "find()", but still not working. Can someone tell me whether I made a mistake or what?

In this case, I want to return only "info" field

const mongodb = require('mongodb').MongoClient
...
db_main.collection('info').findOne({ _id: '123456789' }, { info: 1 }, function(err, result) {
    console.log(result)
})

The document look something like this:

_id: '123456789',
title: 'I love title',
content: 'content here',
info: {
    date: '1/1/2018',
    user: 'username'
}
like image 572
alanko Avatar asked Aug 12 '18 08:08

alanko


People also ask

What does findOne return MongoDB?

findOne() method returns a Promise that resolves to the first document in the collection that matches the query. If no documents match the specified query, the promise resolves to null .

Is findOne deprecated?

It looks like findOne() is only deprecated in the Javascript driver. Worse, MongoDB node driver uses findOne internally extensively. The change was made last year, as part of a series of commits carrying the helpful message "clean up docs".

How does findOne work in MongoDB?

MongoDB – FindOne() Method. The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.

How do I fetch one record in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

You are not using the projection option:

{projection: { info: true }}

The way you are doing

{info:1}

It means you are requesting to use an index on info (if it exist)

like image 194
Giona Granata Avatar answered Oct 04 '22 17:10

Giona Granata