Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my folder structure:

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

My code in file songs.js

var mongoose = require('mongoose') , Schema = mongoose.Schema , ObjectId = Schema.ObjectId;  var SongSchema = new Schema({ name: {type: String, default: 'songname'} , link: {type: String, default: './data/train.mp3'} , date: {type: Date, default: Date.now()} , position: {type: Number, default: 0} , weekOnChart: {type: Number, default: 0} , listend: {type: Number, default: 0} });  module.exports = mongoose.model('Song', SongSchema); 

And here is my code in file albums.js

var mongoose = require('mongoose') , Schema = mongoose.Schema , ObjectId = Schema.ObjectId;  var AlbumSchema = new Schema({ name: {type: String, default: 'songname'} , thumbnail: {type:String, default: './images/U1.jpg'} , date: {type: Date, default: Date.now()} , songs: [SongSchema] });  module.exports = mongoose.model('Album', AlbumSchema); 


How can I make albums.js know SongSchema to be defined AlbumSchema

like image 657
Huy Tran Avatar asked Jan 04 '12 16:01

Huy Tran


People also ask

What is the difference between a Mongoose schema and model?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Is Mongoose schema based?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

What is ref schema?

ref basically means that mongoose would store the ObjectId values and when you call populate using those ObjectIds would fetch and fill the documents for you. So in this case: stories: [{ type: Schema.


1 Answers

You can get models defined elsewhere directly with Mongoose:

require('mongoose').model(name_of_model) 

To get the schema in your example in albums.js you can do this:

var SongSchema = require('mongoose').model('Song').schema 
like image 68
alessioalex Avatar answered Sep 20 '22 06:09

alessioalex