简体   繁体   中英

Error while exporting using node and mongoose

So, I have create some schema like following and exporting the model,

var mongoose = require('mongoose');


var specSchema = new mongoose.Schema({
    name: String,
    description:String
});

var qualSchema = new mongoose.Schema({
    name: String,
    description:String
});


var doctorSchema = new mongoose.Schema({
    name: String,

    // qualifications:[qualSchema],
    // specializations:[specSchema]
});

var Doctor = mongoose.model('Doctor',doctorSchema);
module.exports = Doctor/**please see here**/

This works fine.

However later i thought that I would like to export the schema also from this js file, so i changed the last line as follows:

module.exports = {Doctor,doctorSchema}

My code started failing, then i realised that if I write

module.exports = {Doctor} /**i.e add curly braces to it**/

my code fails again.

This is how we export in node ? right? but this is failing my code.

How are you importing the schema? You should extract the schema name using the dot notation since you are exporting an object.

const Doctor = require('exportedSchemaPath').Doctor;

You can export model and schema as follows:

First Option:

module.exports = Doctor

Import as

const Doctor = require('exportedSchemaFilePath')

Second Option:

module.exports = {Doctor,doctorSchema}

Import as

const {Doctor, DoctorSchema} = require('exportedSchemaFilePath')

As you are exporting as JSON object

Third option:

module.exports = {Doctor} 

import as

const {Doctor} = require('exportedSchemaFilePath')

You just need to change require option as you change export methods

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