node.js - find() 方法不适用于猫鼬中的异步函数
问题描述
我正在尝试在命令提示符下或简单地获取所有文档 console.log() 但 find() 方法在这里不起作用是我的代码以及它在运行时显示的内容。
const mongoose = require('mongoose');
//connection creation and create a new db
mongoose.connect("mongodb://localhost:27017/mohitChannel").then(()=> console.log("connection successful")).catch((err) => console.log(err));
// these then and catch are the promise taker
// and now schema
const playListSchema = mongoose.Schema({
// name: String, there are two ways one it is and other is given below.
name: {
type: String,
required: true
},
videos: Number,
active: Boolean,
author: String,
date: {
type: Date,
default: Date.now
}
})
const Playlist = mongoose.model("PlayList", playListSchema); // collection named playlists created.
const getDocument = async () => {
const result = await Playlist.find()
console.log(result);
}
getDocument();
它显示了这一点
C:\nodeMongo>node src/app.js 连接成功 (node:16088) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" 在 Collection.find (C:\nodeMongo\node_modules\mongodb\lib) 接受最多两个参数\collection.js:238:19) 在 NativeCollection。[as find] (C:\nodeMongo\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:191:33) 在 NativeCollection.Collection.doQueue (C:\nodeMongo\node_modules\mongoose\lib\ collection.js:135:23) 在 C:\nodeMongo\node_modules\mongoose\lib\collection.js:82:24 在 processTicksAndRejections (internal/process/task_queues.js:77:11) (使用node --trace-warnings ...
显示警告的创建位置)(节点:16088)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict
(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝 ID:1)(节点:16088)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。
我尝试了 catch 块,但仍然无法正常工作
解决方案
当您使用 执行脚本时node src/app.js
,您执行的getDocument()
行将在设置 mongodb 数据库连接之前运行,
您正在使用承诺连接到 mongo 数据库,这是在后台发生的异步任务:mongoose.connect(...).then(...)
mongoose.connect
开始执行,因为没有什么可以阻止你的脚本“等待数据库连接”,它将继续到下一行,直到它到达getDocument()
,此时,与数据库的连接尚未设置,这就是你收到错误的原因(在这种情况下,错误消息没有帮助),
要解决您的问题,您可以移动 中的所有内容mongoose.connect(...).then(<all-code-here>)
,如下所示:
const mongoose = require('mongoose');
//connection creation and create a new db
mongoose
.connect('mongodb://localhost:27017/mohitChannel')
.then(() => {
console.log('connection successful');
// and now schema
const playListSchema = mongoose.Schema({
// name: String, there are two ways one it is and other is given below.
name: {
type: String,
required: true,
},
videos: Number,
active: Boolean,
author: String,
date: {
type: Date,
default: Date.now,
},
});
const Playlist = mongoose.model('PlayList', playListSchema); // collection named playlists created.
const getDocument = async () => {
const result = await Playlist.find();
console.log(result);
};
getDocument();
})
.catch((err) => console.log(err));
// these then and catch are the promise taker
并且由于您使用的是async
函数,因此您可以转换async
/await
模式中的所有内容:
const mongoose = require('mongoose');
async function main() {
await mongoose.connect('mongodb://localhost:27017/mohitChannel');
console.log('connection successful');
const playListSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
videos: Number,
active: Boolean,
author: String,
date: {
type: Date,
default: Date.now,
},
});
const Playlist = mongoose.model('PlayList', playListSchema);
const getDocument = async () => {
const result = await Playlist.find();
console.log(result);
};
getDocument();
}
try {
main();
} catch (err) {
// in case the database connection fails, do something
console.log(err);
}
推荐阅读
- angular - Angular CLI 8.2.2 中未显示主题化图标
- android - 为什么视图动画没有消失
- html - 为什么 transform: translateX 会影响移动设备上固定元素的高度?
- awk - 如何在awk中以十六进制格式输入和输出?
- angular - 什么是 autoTableHtmlToJson 以及在哪里转换 html 页面?
- c# - SelectPdf 仅在自定义页面上显示页脚
- python - S3 中的 SageMaker 估计器`source_dir`
- actionscript-3 - 如何在 Adobe Flex 中使用分组数据创建自定义下拉列表?
- android - 如何更新设备上已经存在的 SQLite 表?
- g1ant - 为什么 G1ANT 中的相同代码在不同的迭代中显示不同的结果?