Mongoose通过Model查询文档时出现collection.find()参数错误如何解决?
报错诱因
- 直接原因:你使用的是Mongoose 6.x及以上版本,该版本对
Model.find()的传参规则做了调整:方法第一个参数必须是查询条件对象,回调函数只能作为第二个参数传入。你现在直接把回调函数作为唯一参数传给find(),不符合参数规范,触发底层MongoDB原生方法的参数校验报错。 - 隐藏逻辑问题:
person.save()是异步操作,你当前的写法会在save执行完成前就触发find查询,就算语法修正后也大概率查不到刚插入的John数据。
修复方案
两种常用写法都可以实现需求:
写法1:回调写法(匹配原有代码风格)
修改find传参,同时将查询逻辑放到save的回调中保证执行顺序:
const mongoose = require('mongoose'); // 新增连接异常监听 mongoose.connect('mongodb://localhost:27017/test') .catch(err => console.log('连接失败:', err)); const personSchema = new mongoose.Schema({ name: String, age: Number, }); const Person = mongoose.model('Person', personSchema); const person = new Person({ name: 'John', age: 25, }); person.save().then(()=> { console.log('inserted'); // 第一个参数传空对象代表查询所有文档 Person.find({}, function (err, docs) { if(err){ console.log(err); }else{ console.log(docs); } }); });
写法2:async/await 写法(更推荐,逻辑更清晰)
const mongoose = require('mongoose'); const personSchema = new mongoose.Schema({ name: String, age: Number, }); const Person = mongoose.model('Person', personSchema); // 用异步自执行函数管理所有异步操作 (async function main() { // 等待连接成功 await mongoose.connect('mongodb://localhost:27017/test'); // 等待数据插入完成 await new Person({ name: 'John', age: 25 }).save(); console.log('inserted'); // 等待查询结果返回 const docs = await Person.find({}); console.log(docs); })().catch(err => console.log('操作异常:', err));
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

