猫鼬,如何从数组中迭代添加子文档数组

Mongoose, how to iteratively add an array of subDocs from an array

问题标题可能没有我想要的那么精确,但它确定了我正在尝试实现的模式的精神。

示例可能是描述此模式的最简单方式。

代码示例

//SUBDOCS.js
/*jslint node:true */
"use strict";
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;


var subDocs = {
    types: {
        images:  new Schema({
            url: {type: String, required: true}
        }),
        colors: new Schema({
            name: {type: String, required: true},
            description: {type: String, required: true}
        }),
        addons: new Schema({
            name: {type: String, required: true},
            description: {type: String, required: true},
            price: {type: Number, required: true}
        })
    }
};

subDocs.keys = function () {
    return Object.keys(this.types);
};

module.exports = subDocs;


//PRODUCT.js
... //Condensed for this example, all requires etc. invoked...
subDocs = require("../models/plugins/product/sub_docs"),
subDocTypes = subDocs.keys(),

var ProductSchema = new Schema({});

subDocTypes.forEach(function (element, index, array) {
    ProductSchema.add({name: element, type: [subDocs.types[element]]});
});

执行 returns 并出现错误消息:

Did you try nesting Schemas? You can only nest using refs or arrays.

因此问题就变成了:有没有更好的方法来调用 add 在此上下文中,它似乎与数组类型有关。

关键要求:

为了向模式添加路径,需要一个对象作为 Schema.add();

的唯一参数

在上面的例子中:

array.forEach(function (element, index, array) {
    var initializer = {};
    initializer[element] = [subDocs.types[element]];

    ProductSchema.add(initializer);
});