如果我有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
)
}
答案 0 :(得分:1)
像往常一样,答案总是比我原先想象的更简单:
<强>模式:强>
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"}
]