Mongoose - 初始化嵌套模式的正确方法

Mongoose - Proper way to initialize nested Schemas

如果我有 3 个模型,一个嵌套在另一个模型中,如下所示,我如何在我的种子数据函数中正确初始化它们?


var Alpha = mongoose.Schema({
  Beta: [Beta],
  A_Field: {type: String}
});

var Beta = mongoose.Schema({
  Charlie: [Charlie],
  A_Field: {type: String}
});

var Charlie = mongoose.Schema({
  A_Field: {type: String}
});

function createSeedData(data) {
   Alpha.find({}).exec(function (err, collection) {
       if (collection.length === 0) {
           data.forEach(function (item) {
          Alpha.create(

           //Alpha's A_Field
           //Beta's A_Field
           //Charlie's A_Field

           )
       }

和往常一样,答案总是比我原先想象的要简单:

模式:

var Alpha = mongoose.Schema({
  Beta: { type: Schema.ObjectId, ref: 'Beta' },
  A_Field: {type: String}
});

var Beta = mongoose.Schema({
  Charlie: { type: Schema.ObjectId, ref: 'Charlie' },
  B_Field: {type: String}
});

var Charlie = mongoose.Schema({
  C_Field: {type: String}
});

seedData.js

var 
   Alpha = require('../models/alpha.server.model'),
   Beta = require('../models/beta.server.model'),
   Charlie = require('../models/charlie.server.model'),
   data = require('../json/data');

   createCharlie(data);
   createBeta(data);
   createAlpha(data);

  function CreateAlpha(data){
    data.forEach(function(item){
      var alpha = new Alpha({
       // no _id designation, mongo will create
       Beta : item.betaId,
       .....
      }).save(function (err) {
         if (err) {
            console.log(err);
        });
     }}

   function CreateBeta(data){
     data.forEach(function(item){
      var beta = new Beta({
      _id : item.betaId,
      Charlie = item.charlieId,
      .....
   }).save(function (err) {
       if (err) {
         console.log(err);
            }
        });
  }}

   function CreateCharlie(data){
     data.forEach(function(item){
        var charlie = new Charlie({
        _id = item.charlieId,
        ....
       }).save(function (err) {
         if (err) {
                console.log(err);
            }
        });
    }}

JSON:

 [
  { "betaId": xxxx, "charlieId": xxxx, "A_Field":"AAA", "B_Field":"BBB", "C_Field":"CCC"}
 ]