skip to Main Content

In my mongodb i already had a collection and document
enter image description here

Now, i want to use this collection in my node-js using mongoose. how we do this.

const mongoose = require("mongoose");
const schema = mongoose.Schema;
const adminLogin = new schema({
name: { type: String, required: true },
password: { type: String, required: true }
})
module.exports = mongoose.model("adminDetails", adminLogin)

while doing this it is creating new collection. Unable to use the existing collection.

2

Answers


  1. Chosen as BEST ANSWER

    Structure in mongodb

    the image 1 is the structure in the MongoDB. I want to read the data from that collection, below is the code using and the URL and output in post man.

    route.get('/adminLogin', (request, response) => {
      const data =  adminDetails.find({}, (err, result) => {
        if (err) {
          console.log(err)
        } else {
          res.json(result)
        }
      })
    })
    

    http://localhost:5000/admin/adminLogin

    Response in postman


    1. At first you need to make a GET method Router in your jsFile.

    like this

    app.get("/mainData", async (req, res) => {
      const menuInfo = await Nutrients.find({});
      res.json(menuInfo);
    });
    
    1. You can set and use VSCode extension "thunderClient"!

    like this

    enter image description here

    1. setting your request method and URI endpoint

    (when you user GET method to get some data in your case, you don’t need to write something in request body)

    1. Then, you can see your data on the ‘response part’ as an Object Data.

    2. If you want to use your data on Front side on your Project, you can use like this!

    (in my case, I used jQuery. )

    function menu_show() {
    $('#result_list').empty()
    $.ajax({
        type: 'GET',
        url: '/mainData',     //you need to write same url with your no3.
        data: {},
        success: function (response) {
            console.log(response)
            let rows = response['menus']
    
            for (let i = 0; i < rows.length; i++) {
                let menuName = rows[i]['menuName']
                console.log(menuName)
            }
        }
    }
    

    This is my answer. Let me know if you’ve solved it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search