【问题标题】:issue with Mongoose assigning JSON to variableMongoose 将 JSON 分配给变量的问题
【发布时间】:2020-08-10 09:28:18
【问题描述】:

提前感谢您阅读本文的任何人。我非常感谢任何和所有的帮助。

所以这是我的第一个应用程序个人应用程序。我在 mongodb.com 上的 Atlas 中设置了一个数据库,我可以毫无问题地写入它。但是当我的应用程序尝试从我的数据库中提取时,我可以让它打印到控制台。但我可以将数据分配给任何变量,以便在我的应用程序的其他任何地方使用。

这是我可以打印到控制台的代码。但不确定我缺少什么设置或包,因此我可以将其存储为局部变量。我正在使用回调函数来返回 api 调用,并且控制台打印输出工作正常。只是不知道下一步该做什么

function getTerms() {
    
    let allTerms = []
    termAdd.find({}, '_id', (err, term) => {
            
            term.map((term) => {
                allTerms.push(term)
                // if I understand Push() correctly this should store my output to allTerms.
            });

            //this works to print out to console in JSON.
            console.log(allTerms, 'getTerms')
            return allTerms;
            
        });
    };
    
    
    if (res.statusCode === 200) {
        //callback function to return the console from the function
        getTerms()

       // when i do a let foo = getTerms() it will return undefined
       //so I am really dont understand how to assign the return from 
      //the function to a variable. 


        //How do I assign this console output to variable to use for output

        console.log('200 statusCode')
    };

        //Random Number Generator
        let ranNum = Math.floor((Math.random() * 10) + 1);
        console.log('random number = ',ranNum);

        res.render('fs', {
            flashCard : 'Test Card',
            items: ranNum
        });
    
});

如果能帮助我链接到这个项目,我在 GitHub 上有完整的代码。

无论如何我都应该使用延迟吗?有人给了我一个建议。但我不明白我在读什么。

【问题讨论】:

  • 我正在尝试了解您要存储的内容;是字符串'200 statusCode'吗?对不起
  • 所以我试图存储 getTerms 函数的返回值。但是当我分配“let foo = getTerms()”时,它会返回并在控制台中统一。那么数据在哪里
  • 我相信在做任何事情之前,你应该分离你的功能; getTerms() 发生的事情太多了。如果我没记错的话,你是不是又在里面给getTerms()打电话了?
  • 你能分享剩下的代码吗?
  • 哦不不不!删除那个。永远不要分享那个链接;它包含您的数据库的 URI 和您的密码。事实上,最好不要共享 .env 中的任何内容,也不要将 .env 文件推送到 Github

标签: javascript node.js mongoose


【解决方案1】:

在此之前,请避免将您的 .env 文件推送到 Github 或公开分享其中的任何内容。

您将获取术语的功能分离到自己的功能中,这很好:

// Get function for all items in mongodb
function allItems(all) {
    let allTerms = []
    termAdd.find({}, 'term', (err, term) => {
            
            term.map((term) => {
                allTerms.push(term)
            });
            //this works to print out to console.
            console.log(allTerms, 'function allTerms')  
            //Question is how to I get this JSON to save to a VAR or be passed to another function
        });
};

首先,我将它重命名为getAllTerms,因为它就是这样做的。而且似乎all 参数不是必需的。

**

无论如何,通常情况下,您只需简单地返回 allTerms 变量:

// Get function for all items in mongodb
function getAllTerms() {
    let allTerms = []
    termAdd.find({}, 'term', (err, term) => {
            
            term.map((term) => {
                allTerms.push(term)
            });
            //this works to print out to console.
            console.log(allTerms, 'function allTerms')  
            //Question is how to I get this JSON to save to a VAR or be passed to another function
        });
    return allTerms
}

但是,这不起作用,因为由于您正在调用数据库,因此数据库可能需要一些时间才能获取术语;在这种情况下,allTerms 可能会返回一个空数组 []

您要做的是等待数据库返回术语,将它们推入allTerms数组,最后返回。

// Get function for all items in mongodb
async function getAllTerms() {
    let allTerms = []
    const fetchedTerms = await termAdd.find({}, 'term')
    fetchedTerms.forEach(fetchedTerm => allTerms.push(fetchedTerm))
    return allTerms
}

如果你不知道 asyncawait 是什么,不用担心,here is a good article explaining the why and when to use them.

如果您还有任何问题,请告诉我。

【讨论】:

  • 嘿伙计,非常感谢您的帮助。但我觉得我遇到了同样的错误。项目在控制台中显示的位置。但它们并没有被传递到屏幕上。在我的网页上,我收到 [object Promise] 我是否必须在函数回调中或在函数回调中进行某种类型的查看才能使这些信息可用?
  • @AugustoRodriguez 在您拨打getAllTerms() 时尝试使用asyncawait
  • 感谢您的帮助。明天我会继续努力。看来我必须了解异步并等待。
  • @AugustoRodriguez 没问题,如果您有任何其他问题,请告诉我
  • 嘿,感谢您的所有帮助。我现在可以使用这些变量作为我的页面上带有把手的内容。
【解决方案2】:

使用 Async/Await 可以将上面的代码优化为下面的代码:

`

async function getTerms() {
    //using async/await 
    try{
    const terms = await termAdd.find({}, '_id')
    const allTerms = terms.map((term)=>term)
    // return allTerms here
    return allTerms
    }catch(err){
      throw err
    }
 }

`

有关 Async/Await 的更多见解here 是一本不错的读物

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2014-05-11
    • 1970-01-01
    相关资源
    最近更新 更多