【问题标题】:How to call Mongoose Find function to fetch all of the documents as an array?如何调用 Mongoose Find 函数将所有文档作为数组获取?
【发布时间】:2020-05-31 21:03:17
【问题描述】:

我还是 Node.js 和 Mongoose 的新手,不知道为什么这段代码没有返回数组。有什么建议吗?

function all(array){
    array = card.cards.find({}, (err, items) => {
        array = items
        return array
    })
}

let arr = []
all(arr)
console.log(arr)

最终结果只是一个空数组。

【问题讨论】:

标签: javascript mongoose async-await es6-promise mutability


【解决方案1】:

你不需要传入一个数组,你可以返回 .find() 方法返回的项目。

function getAll(){
    card.cards.find({})
         .then(items => {
             return items 
         }
         .catch(err => {
             console.log(err)
         }
}

【讨论】:

  • 您的代码将无法工作,因为您仍然没有返回结果。正确答案是function getAll() { return card.cards.find({}); }
【解决方案2】:

你有 2 个问题。

1。无法重新分配作为函数内部参数传递的变量:

var a = 1;
function fn(b) {
  b = 2;
}
fn(a);
a === 1; // true

此外,在函数内部并不真正需要时对数据进行变异也是一种糟糕的模式。最好只在外部范围内返回和分配:

function all() {
  return card.cards.find({});
}
all(a).then(console.log); // [...]

但是你可以在不重新分配的情况下改变一个数组:

var a = [1, 2, 3];
function fn(array) {
  array.splice(0, Infinity, ...[5, 6, 7, 8]);
}
a; // [1, 2, 3]
fn(a);
a; // [5, 6, 7, 8]

2。对 Mongoose 和 async-await/promises 的异步调用

即使你从函数 all 返回,你也必须等待结果。

对 mongoose 方法的调用是异步的。这意味着它们返回 Promise 对象(或 Promise),这些对象实现了与方法 thencatch 的接口。你传递给then方法的函数会在promise被解析成功时被调用,catch中的函数会在promise被拒绝时被调用。

例如

function p() {
  if (Math.random() > 0.5) {
    return Promise.resolve(1);
  } else {
    return Promise.reject(new Error('2'));
  }
}

p()
  .then(function (result) { /* will be called half of time for resolve branch */ })
  .catch(function (error) { /* will be called for reject branch */ })

此代码类似于但使用语法糖:

async function p() {
  if (Math.random() > 0.5) return 1; // Similar to return Promise.resolve(1);
  throw new Error('2'); // Similar to return Promise.reject(new Error('2'))
}

要在异步函数中等待 promise,有一个 await 关键字。

async function all() {
  try {
    return await cards.find({});

  } catch(error) {
    if (false /* somehow handle mongoose errors */) {
      // check error, if db not ready just retry or do sth else
      // …
    }

    // Just rethrow if we can't do any
    throw error;
  }
}

阅读更多关于异步等待的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多