我是MongoDB Atlas的新手。我试图使用猫鼬查询我的“ test2”数据库中当前存在的集合“ dogs”。
我正在使用nodeJS执行查询
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://*****:*******b@cluster0-uln4x.mongodb.net/test?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!!!'))
.catch(err => {
console.log('did not work'); });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
db.dogs.find().forEach(printjson); //ERROR!
});
这将导致错误:TypeError: Cannot read property 'find' of undefined
undefined
的狗怎么样?
答案 0 :(得分:1)
在您的代码dogs
中必须是猫鼬模型,还将mongoDB连接字符串更改为test2
,请尝试以下操作:
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://*****:*******b@cluster0-uln4x.mongodb.net/test2?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!!!'))
.catch(err => {
console.log('did not work', err);
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
const dogsSchema = new mongoose.Schema({
any: {}
});
const Dogs = mongoose.model('dogs', dogsSchema, 'dogs');
db.once('open', function () {
Dogs.find().lean(true).exec((err, data) => {
console.log('Err ::', err, 'data ::', data)
})
});