Can i get back a formated json response when i do Model.find({}) to find all documents with mongoose?

Tell us what’s happening:
I want to get back a response like this , //JSON res format: [{"_id": data._id, “title”: data.title}] . But it returns the whole collection, I can’t get back a selective item like only the title from the collection.

My code snippet

Your code so far

const bookSchema = new mongoose.Schema({
  title: String,
  comments: []
})

const Books = mongoose.model("Books", bookSchema);
module.exports = function (app) {

  app.route('/api/books')
    .get(function (req, res){
      //response will be array of book objects
      //json res format: [{"_id": bookid, "title": book_title, "commentcount": num_of_comments },...]
    Books.find({}, (err, data) => {
      res.json(data.title)
    })
    })
  
    .post(function (req, res){
      var title = req.body.title;
      //response will contain new book object including atleast _id and title
    const newBookTitle = new Books({
      title
    })
    newBookTitle.save(function(err, booksData) {
      if(err) return res.json(err)
      res.json(booksData)
    })
    })

data.title returns null value?
Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Personal Library

Link to the challenge:

Hey there, You can get a single option and returning using

.findOne(query, function(err,obj) {
res.json(obj); });

where query is the key-value pair to be used to search and identify the single item

This will return just only a specific item, but i want to return all the title stored in my documents.

You want all the titles in your database?
If so you could iterate the json and push all the titles to a new array/object that you can then return.

1 Like

I tried this it returns an empty array. Can you show me a example how to do it ?

Ouky i got it man. Thanks for the help it worked.

1 Like

you are welcome @n3tspid3r. Happy coding

1 Like