简体   繁体   English

从mongodb查询所有元素的函数不会填充数组

[英]function querying all elements from mongodb does not populate array

so i've written a function that should query everything in the files inventory of my mongodb using mongoose, but instead... doesn't. 因此,我编写了一个函数,该函数应该使用mongoose查询mongodb的files清单中的所有内容,但是……不是。 while each element is in fact being read, files.push() doesn't seem to have any effect on the array, as the array is still empty. 尽管实际上正在读取每个元素,但files.push()似乎对数组没有任何影响,因为数组仍然为空。

while i know that console.log() is not an effective way to debug, considering express still does not render the contents of the array, it is in fact not being populated. 虽然我知道console.log()并不是一种有效的调试方法,但考虑到express仍然无法呈现数组的内容,实际上它并未被填充。

yes, it is being called as getAllFiles(Image) . 是的,它被称为getAllFiles(Image)

code below: 下面的代码:

const Image = module.exports = mongoose.model('files', imageSchema);

function getAllFiles(collection) {
  let files = [];

  collection.find({}, (err, buns) => {    
    buns.forEach((bun) => {
      let fin = bun.path.replace("public/", "");
      files.push(fin);
      console.log(fin);
    });
  });

  console.log(files);
  return files;
}

terminal output (ignore extraneous outputs): 终端输出(忽略无关输出):

wildflower :: src/bunnydb » node app.js
(node:23296) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.running on port 3000
[]
uploads/9160d961-3d9b-4dea-a39c-f79b86647408.jpg

was able to fix by adding a callback as it was running asynchronously: 通过添加一个异步运行的回调得以修复:

function getAllFiles(collection, cb) {
  let files = [];

  collection.find({}, (err, buns) => {    
    console.log('err: ' + err);
    console.log('buns: ' + buns);
    buns.forEach((bun) => {
      let fin = bun.path.replace("public/", "");
      files.push(fin);
      console.log('data: ' + fin);
    });
    cb(files);
  });

  console.log('arr: ' + files);
  return files;
}

and on invocation the callback argument can be used to do stuff with the files 并且在调用时,可以使用callback参数对文件进行处理

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

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