Node.js MongoDB collection.find()toArray不返回任何内容

【字号: 日期:2024-04-16浏览:41作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决Node.js MongoDB collection.find()toArray不返回任何内容?

最好的方法是使用Promises。像这样做。

function getUsers () { return new Promise(function(resolve, reject) { database.collection('customers').find().toArray( function(err, docs) { if (err) {// Reject the Promise with an errorreturn reject(err) } // Resolve (or fulfill) the promise with data return resolve(docs) }) })}解决方法

尽管我发现了与我类似的问题,但我无法独自解决问题。

在我的’../models/user’模型中,我想找到所有用户并将其放入数组,然后将该数组返回给控制器(在这里我将使用信息)。

这是我的代码:

var mongoDatabase = require(’../db’);var database = mongoDatabase.getDb();function find() { var test; database.collection('customers').find().toArray( function(err,docs) {if(err) throw err;console.log(docs); //works fine //I’d like to return docs array to the callertest = docs; }); console.log(test); //test is undefined }module.exports = { find};

我还注意到,“ console.log(test)”位于“console.log(docs)”之前。我尝试将’docs’参数作为函数参数传递给’find’,但没有结果。

相关文章: