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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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'





Projection doesn't work with the new node mongodb driver... Instead you have to use .project() cursor method here... stackoverflow.com/questions/51732527/…
– Anthony Winzlet
Aug 12 at 8:58


.project()




3 Answers
3



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)



You can do one more thing if you want only one field.. Add Title:0, content:0 with info:1



use the aggregate function to get what you need. use this link for more reference. The example is given below


db_main.collection('info').aggregate([ match:_id: '123456789' ,project:info:1], function(err, result)
console.log(result)
)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS