javascript - 为什么dbs调用后数组变量没有保存-node js

标签 javascript node.js mongodb mongoose

我有一个保存 Cat 信息的架构。然后我想创建一个包含所有 cat_url 的数组,但是当我在 dbs 调用之外调用该数组时,该数组为空

var cat_urls = [];

Cat.find(function (err, data) {
    var stringify = JSON.stringify(data)
    content = JSON.parse(stringify);
    content.forEach(function (result) {
        cat_urls.push(result.cat_url);
    })
    console.log(cat_urls, 'here')
})

console.log(cat_urls, 'here not working') // I want cat_urls to also be populated here

因此在 Cat.find() 调用 cat_urls 中具有如下值:

[ 'www.hello.co.uk', 'www.testing.co.uk' ] 'here'

但是在cat_urls = []之外

我猜这与 Node js 不按特定顺序运行有关,但我该如何解决这个问题?

最佳答案

我认为它有效,但您的 find 函数返回一个异步解析的 promise 。

尝试:

var cat_urls = [];

Cat.find(function (err, data) {
    var stringify = JSON.stringify(data)
    content = JSON.parse(stringify);
    content.forEach(function (result) {
        cat_urls.push(result.cat_url);
    })
    console.log(cat_urls, 'here')
}).then(function(){
  // Promise has completed, now this console log will trigger only after the cat's names are pushed.
  console.log(cat_urls);
})

关于javascript - 为什么dbs调用后数组变量没有保存-node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003524/

相关文章:

node.js - Heroku Node Express Stormpath 'API key ID and secret is required'

javascript - 获取表格内的输入标签

javascript - jQuery sortable - 在 ('dblclick' 上绑定(bind)新的)到克隆的元素

Javascript/jquery - 添加一个类以在可变位置列出

node.js - 如何从App Engine获取真实请求客户端的IP

node.js - Strongloop Oracle 通过脚本连接

mongodb - Go Mongo Driver 检索无模式文档

javascript - 在 Node 中插入新的 mongo 文档时保存不带 ObjectID 部分的 _id

javascript - 更新 Meteor 用户配置文件中的购物车对象

javascript - 在线展示3D模型