user2830412
user2830412

Reputation: 65

How i can convert mongoose json result to array?

I have a sample code that shows the result and want to convert the result into array.

TranModel
        .find({ quantityout: 1 }, 
                        { _id: 0} )
        .sort({ tag: 1 })
        .select( 'tag' )
        .populate( 'createdby' )
        .exec(function(err, data){
            if(err){
                res.json(err)
            } else {
                res.json(data)
            }
        })

Result

[
  {
    "tag": "TH000001"
  },
  {
    "tag": "TH000006"
  },
  {
    "tag": "TH000009"
  },
  {
    "tag": "TH000011"
  },
  {
    "tag": "TH000014"
  }
]

And I need convert result to like this

[
  "TH000001",
  "TH000006",
  "TH000009",
  "TH000011",
  "TH000014"
]

Upvotes: 1

Views: 10208

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You can't get that directly from a Mongoose find query, but you manipulate the output using the JavaScript Array.map function to get what you're looking for:

TranModel
    .find({ quantityout: 1 }, 
          { _id: 0} )
    .sort({ tag: 1 })
    .select( 'tag' )
    .exec(function(err, docs){
        docs = docs.map(function(doc) { return doc.tag; });
        if(err){
            res.json(err)
        } else {
            res.json(docs)
        }
    })

I took out the populate call because that doesn't make any sense here because you're not including createdBy in the output.

Upvotes: 6

Related Questions