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

问题描述 投票:47回答:4

这是我的文件夹结构:

+-- 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);

如何制作albums.js知道SongSchema被定义为AlbumSchema

javascript node.js mongodb mongoose nosql
4个回答
87
投票

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

require('mongoose').model(name_of_model)

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

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

25
投票

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

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

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

你的albums.js上面的代码行肯定会奏效。


2
投票

对于其他不熟悉Mongoose如何工作的深层方面的人来说,现有的答案可能会令人困惑。

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

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

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

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

从这里,我可以看到你首先访问并要求文件通常如何需要模型,除了在这种情况下你现在专门访问该模型的模式。

其他答案需要变量声明中的mongoose,这与通常发现需要mongoose的例子相反,之后通过声明变量如const mongoose = require('mongoose');然后使用像这样的mongoose。这样的用例对我来说无法获得知识。


Alternative option

您可以像通常那样只需要模型,然后通过Model的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]
});
© www.soinside.com 2019 - 2024. All rights reserved.