简体   繁体   中英

Getting NULL data from collection from MongoDB Atlas

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();
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM