如何获取在另一个模型中定义的mongoose数据库的Schema

时间:2012-01-04 16:30:04

标签: javascript node.js mongodb mongoose nosql

这是我的文件夹结构:

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

我的代码在文件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);

这是我的文件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);


如何制作专辑.js知道 SongSchema 定义为AlbumSchema

5 个答案:

答案 0 :(得分:84)

您可以直接使用Mongoose获取其他地方定义的模型:

require('mongoose').model(name_of_model)

要在albums.js中获取示例中的架构,您可以执行以下操作:

var SongSchema = require('mongoose').model('Song').schema

答案 1 :(得分:24)

要从已注册的Mongoose模型获取架构,您需要专门访问架构:

var SongSchema = require('mongoose').model('Song').schema;

答案 2 :(得分:3)

var SongSchema = require('mongoose').model('Song').schema;

albums.js中的上述代码行肯定会有效。

答案 3 :(得分:1)

对于其他不熟悉猫鼬工作原理的其他人,现有答案可能会令人困惑。

这是一个通用实现示例,该示例从另一个文件中导入模式,该文件可供更广泛背景下的更广泛受众访问。

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

这是问题中特定案例的修改版本(将在内部 albums.js中使用)。

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

由此,我可以看到您首先访问并要求该文件正常情况下将需要一个模型,除非在这种情况下,您现在专门访问该模型的架构。

其他答案要求在变量声明中使用猫鼬 ,这与在声明诸如const mongoose = require('mongoose');之类的变量然后再使用猫鼬之前要求猫鼬的常见示例相反。对我而言,这种用例在知识上是无法访问的。


替代选项

您可以像往常一样要求只是模型,然后通过模型的schema属性引用该模式。

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]
});

答案 4 :(得分:0)

"songs" : [{type: Schema.Types.ObjectId, ref: 'Song', required: true}]