Aastha
Aastha

Reputation: 43

access fields in a collection in mongodb

i am using nodejs and mongodb

    "image" :
    "comments" : 
    "date" : 
    "name" : 
    "description" :
    "author" : {
        "id" : 
        "username" : 
    },
    "user" 
    "__v" 
}

these are the fields in my collection named Blog.
i want to access the username

Blog.find({author.username:req.params.username}

i tried doing it like above but am getting error.
How can i access the username from inside author

Upvotes: 0

Views: 55

Answers (2)

Amila Sampath
Amila Sampath

Reputation: 16

Ref : https://www.npmjs.com/package/mongoose

// Blog Schema 
{
"description" : { type : string },
"author" : {
    "id" : string
    "username" : string, 
    "type": { type : string } // auther is an object with a type property
 }
}

// Blog find query 
const username = req.params.username  // user name 
Blog.find({"author.username" : username }, (err, data) => {
  if(err) {
    // error handler 
  }else{
    console.log(data)
  }
}

Upvotes: 0

Taymer
Taymer

Reputation: 314

It looks like you have made a typo. You are using account, but in the schema it is author. Try this:

Blog.find({author.username:req.params.username}

Upvotes: 1

Related Questions