问题
I have connected my code to MongoDB Atlas using Mongoose... even though the collection has a data in it its shows null in response.
I want to know the exact issue and troubleshoot it, because the collection has the data required
Collection details are in this image:
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();
});
回答1:
It's because the mongoose
instances in your Connectivity Code
and Model
are different and unrelated. One is connected (Connectivity), but the other (Model) is not. You've to use the same instance so export one mongoose
and import that where required.
// 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
来源:https://stackoverflow.com/questions/55858975/getting-null-data-from-collection-from-mongodb-atlas