简体   繁体   中英

How to get data from model in node express?

I'm new to MERN and stackoverflow. I want to get all data from mongodb database. But when I try it through postman, It shows following error.

在此处输入图像描述

Here is my Model.js file Model.js

const mongoose = require("mongoose");

const Schema = {
    name: {
        type: String,
        required: true
    },
    code: {
        type: String,
        required: true
    },
    passMark: {
        type: Number,
        required: true
    },
    lic: {
        type: String,
        required: true
    },
    subjects: [
        { 
            type: mongoose.Schema.Types.ObjectId, 
            required: false, 
            ref: 'Subjects' 
        }
    ]
};

const Model= mongoose.model("Model",Schema);

module.exports = Model;

Here is my router.js file Router.js

const Model= require("../models/Model");
const route = require("express").Router();

route.get("/", (req,res)=>{
    Model.find()
   .exec((err, items)=>{
        if(!err){
            return res.json({items: items})
        }
    })
});

Someone can help me to fix this issue.

That's a blind guess, but I believe the error occurs because Model.find() does not return JSON data. It returns a collection of Mongoose objects, with extra methods like .save() . If you want pure JSON out of Mongo, add .lean() :

route.get("/", (req,res)=>{
    Model.find().lean()
   .exec((err, items)=>{
        if(!err){
            return res.json({items: items})
        }
    })
});

Pro tip, same thing using the async/await syntax:

route.get("/", async (req,res)=>{
   try{
       const items = await Model.find().lean().exec(); // .exec() returns a true Promise
       res.json({items});
   } catch(err) {
      res.status(500).end(err)
   }
});

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