简体   繁体   English

如何在 collection.find() 之后获取 JSON object

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

I'm using nodeJS to get data from mongoatlas with an URL.我正在使用 nodeJS 通过 URL 从mongoatlas获取数据。

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() .但是,在 function collection.find()之后,我不知道如何将我得到的数据转换为 JSON object ,然后再进行stringify()

The variable record is undefined and I don't know how to assign it properly.变量record未定义,我不知道如何正确分配它。

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.如我所见,收集方法“查找”返回 promise,请尝试等待。

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

Also, check the interface of this method, it could take a callback fn as an argument.另外,检查此方法的接口,它可以将回调 fn 作为参数。

Use lean使用lean

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

This will produce a json object, which then can be stringified easily.这将产生一个 json object,然后可以轻松地对其进行字符串化。

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 });
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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