简体   繁体   中英

How to get the JSON object after collection.find()

I'm using nodeJS to get data from mongoatlas with an URL.

However, after the function collection.find() , I have no idea how to turn the data I get into JSON object that later to be stringify() .

The variable record is undefined and I don't know how to assign it properly.

Code are as follow:

app.get("/allbooks", (request, response) => {
    console.log("someone request to get all books from database")
    var records = collection.find()
    if(records!=null){
        console.log('not empty')
    }
    var result
    records.forEach(function(record) {
        if(record!=null) {
            console.log(record)
            result = result + JSON.stringify(record)
        }
    }, function(err) {
        if(err) {
            response.status(500).send(err)
        }
    console.log(result)
    response.send(result)
    })
})

As I can see, the collection method "find" returns promise, try to await that.

const records = await collection.find();  
console.log(records);

Also, check the interface of this method, it could take a callback fn as an argument.

Use lean

const records = await collection.find().lean()

This will produce a json object, which then can be stringified easily.

You can change and simplify your code like this:

app.get("/allbooks", async (request, response) => {
  try {
    let records = await collection.find({});
    res.status(200).send(JSON.stringify(records));
  } catch (error) {
    res.status(400).json({ error: error });
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM