How to get Schema of mongoose database which defined in another model

后端 未结 5 1205
南笙
南笙 2020-12-07 12:32

This is my folder structure:

+-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.js
|---- and another files of expressjs
         


        
5条回答
  •  悲哀的现实
    2020-12-07 13:17

    For others not as familiar with the deeper aspects of how Mongoose works, the existing answers can be confusing.

    Here's a generalized implementation example of importing a schema from another file that is accessible to a wider audience coming from a more general context.

    const modelSchema = require('./model.js').model('Model').schema
    

    Here's a modified version for the specific case in the question (this would be used inside albums.js).

    const SongSchema = require('./songs.js').model('Song').schema
    

    From this, I can see that you first access and require the file how one would normally go about requiring a model, except in this case you now specifically access the schema of that model.

    Other answers require mongoose within the variable declaration and that goes against the commonly found example of requiring mongoose before through declaring a variable such as const mongoose = require('mongoose'); and then using mongoose like that. Such a use case was not accessible knowledge-wise to me.


    Alternative option

    You can require just the model like you normally would and then refer to the schema through the Model's schema property.

    const mongoose = require('mongoose');
    
    // bring in Song model
    const Song = require('./songs.js');
    
    const AlbumSchema = new Schema({
        // access built in schema property of a model
        songs: [Song.schema]
    });
    

提交回复
热议问题