简体   繁体   中英

Mongoose/Express Get all subdocuments api

So I feel foolish for asking this, and I know there are a ton of related posts on this, but I cannot find anything to work. I'm guessing that it has to do with the index.js since Postman is saying it cannot even connect to the route. I have 2 routes, and the clientRoutes works just fine, postman returns and it shows up on my frontend. However, making any call to the contractRoutes gets me nothing.

I'm trying to pull all 'contracts' subdocs for a single client. I'm new to Express/Mongoose and I'm guessing that I've missed something totally obvious.

index.js

const express = require("express")
const mongoose = require("mongoose")
const cors = require('cors')
const clientRoutes = require("./routes/clientRoutes")
const contractRoutes = require("./routes/contractRoutes")
const bodyParser = require('body-parser');

mongoose
    .connect("mongodb+srv://admin:oneterra@cluster0.0cajn.mongodb.net/Octotest?retryWrites=true&w=majority", { useNewUrlParser: true })
    .then(() => {
        const app = express()
        app.use(express.json())
        app.use(cors())
        app.use(bodyParser.json());
        app.use("/api", clientRoutes)
        app.use("/api", contractRoutes)

        app.listen(5000, () => {
        console.log("Server has started")   
        })

})

client model

const mongoose = require("mongoose")

const schema = mongoose.Schema({
    clientId: Number,
    firstName: String,
    lastName: String,
    phone: String,
    contracts: [{
        contractId: Number,
        authNumber: String,
        contType: String,
        contHours: Number,
        contStartDate: Date,
        contEndDate: Date
    }],

})

module.exports = mongoose.model("Client", schema)

clientRoutes - which works as expected

const express = require("express")
const Client = require("../models/Client.js")
const router = express.Router()


//Client routes
router.get("/clients", async (req, res) => {
    const clients = await Client.find()
    res.send(clients)
})

router.get("/clients/:clientId", async (req, res) => {
   try {
    const client = await Client.findOne({ clientId: req.params.clientId })
    res.send(client)
   } catch {
       res.status(404)
       res.send({ error: "Client not found"})
   }
})

contractRoutes which only brings the error "Cannot GET /api/clients/1/contracts" (1 being the clientId, which has contracts in the db). On clientRoutes, from the first tutorial I used, I did not put '' around ({ clientId: req.params.clientId). In the code below I have it there when I was trying to figure this out, but I get the same result, and again seems to show I'm missing something at the top level.

const express = require("express")
const Client = require("../models/Client")
const router = express.Router()

  try{
        const client = await Client.findOne({ 'clientId': req.params.clientId })
        const contracts = client.contracts;
        res.send(contracts)  
    } catch {
        res.status(404)
        res.send({error: "Contracts not found"})
    }

     
       console.log(contracts)

I've tried using populate

Client.findOne({ 'clientId': req.params.clientId })
    .populate('contracts')
    .exec(
        function(err, client) {
            if (err) res.status(500).send(err);

            res.json(client.contracts);
        }
    );

and even if I copy the exact same route for a single client from clientRoutes, but with the contracts endpoint, I get the same error as above

const express = require("express")
const Client = require("../models/Client")
const router = express.Router()


//Client routes
router.get("/clients/:clientId/contracts", async (req, res) => {
    try {
        const client = await Client.findOne({ clientId: req.params.clientId })
        res.send(client)
       } catch {
           res.status(404)
           res.send({ error: "Client not found"})
       }
    })

Any help is greatly appreciated, I've spent hours running in circles on this and trying every type of different way to make the call. But in dialing it down to even using the same route from clientRoutes but with the contracts endpoint and getting the error, I'm assuming it has to due with the index.js server connection.

So in case anyone comes across this with the same issue, as I put in the comment, express wasn't accepting the 2nd route starting with the same path.

By changing

app.use("/api", clientRoutes)
app.use("/api", contractRoutes)

to

app.use("/api", clientRoutes)
app.use("/api/clients", contractRoutes)

then the route worked fine. I did not see anything in the express docs saying that no path can be designated as the same, but making the change made it work, so there's that.

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