我已使用MongoDB Atlas将我的代码连接到Mongoose ...即使该集合中包含数据,其显示的响应也为空。
我想知道确切的问题并进行故障排除,因为该集合具有所需的数据
集合详细信息在此图像中:
1. Connectivity Code -
const mongoose = require('mongoose')
const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/";
mongoose.connect(uri, {
dbName: 'bing_bot'
}).catch((e) => {
console.log('Database connectivity error ', e)
})
2.Model-
const mongoose = require('mongoose')
const Student = mongoose.model('student', {
StudentName: {
type:String
},
Contact: {
type:String
},
Email: {
type:String
},
BNo: {
type:String
},
Year: {
type:String
}
})
module.exports = Student`enter code here`
3. Retrieve data -
Student.findById(_id).then((data) => {
console.log('data: ', data)})
4. Using MongoCLient
const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/bing_bot"
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n', err);
}
console.log('Connected...');
const collection = client.db("bing_bot").collection("student");
// perform actions on the collection object
collection.findOne({
"StudentName": "Test"
}).then((d) => {
console.log('data: ', d)
})
const data = collection.find()
console.log('data:1 ', data)
client.close();
});
答案 0 :(得分:0)
这是因为mongoose
和Connectivity Code
中的Model
实例是不同且不相关的。一个已连接(连通性),但另一个未连接(模型)。您必须使用相同的实例,因此导出一个mongoose
并在需要时导入它。
// connectivityCode.js
const mongoose = require('mongoose')
const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/";
mongoose.connect(uri, {
dbName: 'bing_bot'
}).catch((e)=>{
console.log('Database connectivity error ',e)
})
module.exports = mongoose; // <-- exporting
// model.js
const mongoose = require('./connectivityCode.js') // <-- importing
// rest of the code