简体   繁体   中英

NodeJS RESTful API Import/Require dilemma

I'm currently working on my first node.js/express rest API and I ran into an issue.

I use mongoose to build Schemas, and one of those Schemas requires data (for validation porpuses) from its origin DataBase.

Now I have an import dilemma because at the time I import the Schemas, there is not yet a binding to the DataBase. I tried to import the models from server.js to request Data from the DB. However, I got an error that the model I tried to import is undefined. Hence the Connection to the DB in server.js is not yet established at the time of import.

This here is my server.js , I require the Schemas from ./api/models/newsClassificationHubModel As you can see at the time I import the Schemas I didn't establish the required connection.

//server.js

const express = require("express"),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require("mongoose"),
    schemas = require("./api/models/newsClassificationHubModel"),
    bodyParser = require("body-parser");

// mongoose instance connection url
mongoose.Promise = global.Promise;
TagHubClusterConnection = mongoose.createConnection("mongodb+srv://admin:##########@cluster0.yzl7d.mongodb.net/textClassHub?retryWrites=true&w=majority\n",
    { useNewUrlParser: true, useUnifiedTopology: true });

// export models with custom connections
exports.devSentence = TagHubClusterConnection.model("newSentence_DB", schemas.registerNewSentence)
exports.devTagBase = TagHubClusterConnection.model("baseTag_DB", schemas.registerNewBaseTag)
exports.devTagChild = TagHubClusterConnection.model("childTag_DB", schemas.registerNewChildTag)

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const routes = require("./api/routes/newsClassHubRoutes");
routes(app); // register the route

app.listen(port, "localhost",function() {
    console.log("server is listening on http://localhost:" + port)
})

Here you can see a shortened version of the Schema defenition in ./api/models/newsClassificationHubModel , At this point, I would need to do a request to the DB to get the valid tags from the DB

// newsClassificationHubModel.js (Schemas) 

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// get validTags from DB
let validTags = []


// Schema definition
const registerNewChildTag = new Schema({
    tagID: {
        type: String,
        required: true
    },
    tagName: {
        type: String,
        required: true
    },
    description: {
        type: String,
        validate: [lengthValidator, "Please enter a description with min 30 characters"],
        required: true
    },
    childTag: {
        type: String,
        enum: {
            values: validTags,
            message: "Please enter a valid tagID"
        },
        required: true
    }
});

exports.registerNewChildTag = mongoose.model("childTag_DB", registerNewChildTag);

I believe I could use A promise to solve that problem, yet I don't know how to do it exactly.

I appreciate any hint from anyone, and If something is unclear please don't hesitate to ask for a better explanation

BreadBerry

The problem you have here is that when you import the schema file tries to create a model but there is no connection yet for the app. I think it will work if you move your import down after creating the connection. also importing your models inside the server file is not the best practice.

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