我创建了一个辅助函数,它应该返回一个 promise,该 promise 返回一个字符串数组,表示当前在我的数据库中的所有集合的名称。
我能够通过控制台日志记录验证我是否已成功连接到数据库并且我的名称数组正在填充预期值,但是调用此方法返回未定义。
如何修改它以返回预期结果?
function getCollectionNames() {
mongoose.connect(uri, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', console.error.bind(console, 'Connection error:'))
db.once('open', () => {
return mongoose.connection.db.listCollections().toArray().then( (collections) => {
let names = []
collections.forEach( (col) => { names.push(col.name) })
mongoose.connection.close()
return names
})
})
}
getCollectionNames() // Should return an array of strings.
最佳答案
您所有的数据库操作都是异步的,因此当您的函数返回时,此操作尚未完成(甚至可能尚未开始)。
This is an article这对于理解 JS 处理异步代码的方式非常有用。
您可能还需要了解 arrow functions理解下面的代码。
不知道你是否熟悉Promise
,如果不熟悉,here's a good link .
现在,我假设您熟悉异步代码和 promise 。所以,你需要做的是:
- 连接到您的数据库
- 检索数据并处理它
首先,连接到您的数据库(这是一个异步操作):
const mongoose = require( 'mongoose' );
// just call it once to connect to your DB
const connectToMongoDB = uri => new Promise((resolve, reject) => {
mongoose.connect(uri, { useNewUrlParser: true });
const mongooseCo = mongoose.connection;
mongooseCo.on('error', err => reject(err))
mongooseCo.once('open', () => resolve(mongooseCo));
});
当这个 Promise resolve 时,这意味着你的数据库连接是打开的 (.once('open')
)
下面是这个函数的使用方法:
connectToMongoDB(YOUR_DB_URI)
.then(db => {
/* do what you want with your db */
})
.catch(e => { /* the connection throws an error : e */ })
好的,现在您需要从数据库中获取数据并检索它。过程是相同的:创建一个返回 Promise 的函数并解析 Promise 以获取值。
const getMyCollections = mongooseCo => new Promise((resolve, reject) => {
mongooseCo.db.listCollections().toArray().then(collections => {
const names = collections.map(col => col.name);
resolve(names);
})
});
使用方法如下:
getMyCollections(mongoose.connection)
.then(names => { /* Do what you want with your names */ })
使其协同工作
connectToMongoDB(YOUR_DB_URI)
.then(mongooseCo => {
getMyCollections(mongooseCo)
.then(names => {
/* do what you want with your names */
})
})
更好地使用 Promise chaining :
connectToMongoDB(YOUR_DB_URI)
.then(getMyCollections)
.then(names => {
/* here are your names */
})
希望对你有帮助,
最好的问候
关于javascript - Mongodb(Mongoose)无法返回与数据库中现有集合相对应的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52074088/