Getting multiple data from mongodb with limited fields is an easy process.
Let's see an example. Here is a list of documents in Users
collection.
{
"_id":ObjectId("5ebadc45a99bde77b2efc16a"),
"username":"tradecoder",
"userType":"admin",
"email":"tradecoderbd@gmail.com",
"firstName":"trade",
"lastName":"coder",
"password":"12345678",
"createdAt":"2020-12-13T16:39:30.385Z",
"updatedAt":"2020-12-13T16:39:30.385Z"
},
{
"_id":ObjectId("5ebadc45a99bde77b2efc16b"),
"username":"user2",
"userType":"editor",
"email":"user2@example.com",
"firstName":"first name",
"lastName":"last name",
"password":"12345678",
"createdAt":"2020-12-14T16:39:30.385Z",
"updatedAt":"2020-12-14T16:39:30.385Z"
},
{
"_id":ObjectId("5ebadc45a99bde77b2efc16c"),
"username":"user3",
"userType":"author",
"email":"user3@example.com",
"firstName":"first name",
"lastName":"last name",
"password":"12345678",
"createdAt":"2020-12-15T16:39:30.385Z",
"updatedAt":"2020-12-15T16:39:30.385Z"
}
Now, if we want all the documents from the collection but with limited fields, like,
if we need only the username and userType from all the documents, we can do it by this way
Users.find({}, {username:true, userType:true, _id:0})
This will return an array containing the following data
[
{
"username":"tradecoder",
"userType":"admin"
},
{
"username":"user2",
"userType":"editor"
},
{
"username":"user3",
"userType":"author"
}
]
Node, express, mongodb working code
Here router
is express router
const router = require('express').Router();
and Users
is our database collection
router.route('/api/get-users/')
.get((req, res)=>{
Users.find({}, {username:true, userType:true, _id:0})
.then(data=>res.send(data))
.catch(err=>res.send(err))
})
Read more on TradeCoder : MongoDB Section
If you find this document helpful, please feel free to share it on your networks...