Loading

mongoose 6.0.2 中使用 collection.find()遇到 warning

代码场景

const mongoose = require('mongoose');
//链接本地数据库
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then((result) => {
        console.log('数据库连接成功');
    }).catch((err) => {
        console.log('数据库连接失败')
    });
//创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
//创建集合
const User = mongoose.model('User', userSchema);

User.create({name: '李万年', age: '30'}).then(result => console.log(result));

//此处代码块报错!
User.find({ name: '李万年' }).then(result => {
    console.log(result);
})

报错信息:

(node:12292) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments
    at Collection.find (D:\gh_09\桌面\test\database\node_modules\mongodb\lib\collection.js:238:19)
    at NativeCollection.<computed> [as find] (D:\gh_09\桌面\test\database\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:191:33)
    at NativeCollection.Collection.doQueue (D:\gh_09\桌面\test\database\node_modules\mongoose\lib\collection.js:135:23)
    at D:\gh_09\桌面\test\database\node_modules\mongoose\lib\collection.js:82:24
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12292) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12292) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

解决方案

这个问题是在 mongoose 6.0 版本中遇到的,所以你只需要降级 mongoose 版本。只需运行 npm uninstall mongoose 来卸载当前的 mongoose 版本,然后运行 ​​npm i mongoose@5.13.8 这将安装可以解决您的问题的版本。

javascript - Error when trying to use .find() in Mongoose - Stack Overflow

posted @ 2022-01-30 11:02  Hong•Guo  阅读(132)  评论(0)    收藏  举报