簡體   English   中英

Mongoose子文件在單獨的文件上,如何嵌入它們

[英]Mongoose Sub-documents on separate files, how to embed them

我正在定義我的應用程序模型,我為每個模型定義了單獨的文件,我的問題是,我需要創建一個使用子文檔的模型,但是在另一個文件上,我該如何使用該模式在我的模特? 我的意思是我見過的所有例子都在同一個文件中聲明了Child模型和Parent,例如:

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  children: [childSchema]
});

我有一個名為user.js文件,用於定義用戶模型:

var mongoose  = require('mongoose');
var Schema    = mongoose.Schema;

var userSchema = new Schema({

  _id           : Schema.Types.ObjectId,
  username      : String,

});


module.exports = mongoose.model( 'User', userSchema );

在另一個名為sport.js文件中,我有其他運動模型定義:

var mongoose  = require('mongoose');
var Schema    = mongoose.Schema;

var sportSchema = new Schema({

  _id       : Schema.Types.ObjectId,
  name      : String

});

module.exports = mongoose.model( 'Sport', sportSchema );

所以在我的用戶模型中,我需要為用戶將遵循的體育定義一個字段,但我不知道如何定義該子文檔,因為體育定義在另一個文件上,我試過這個:

var mongoose  = require('mongoose');
var Schema    = mongoose.Schema;
var SportsModel = require('sport');

var userSchema = new Schema({

  _id           : Schema.Types.ObjectId,
  username      : String,
 sports         : [SportsModel]

});


module.exports = mongoose.model( 'User', userSchema );

但我不確定這是否正確,因為我出口的是模型,而不是Schema。

在此先感謝,我想在單獨的文件上定義每個模型以維持秩序。

您可以通過其schema屬性訪問Model的架構。 所以這應該工作:

var userSchema = new Schema({    
  _id           : Schema.Types.ObjectId,
  username      : String,
  sports        : [SportsModel.schema]    
});

使用ref

var mongoose  = require('mongoose');
var Schema    = mongoose.Schema;

var userSchema = new Schema({
    _id     : Schema.Types.ObjectId,
    username: String,
    sports  : [{ type: Schema.Types.ObjectId, ref: 'Sport' }]
});

module.exports = mongoose.model('User', userSchema);

順便說一下,使用ref ,你可以在查詢時使用.populate('sports') ,而mongoose會為你擴展這些類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM