4

Subdocuments (embedded documents) in Mongoose can be specified in a schema like:

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

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

But how do I specify setters on the collection and require that the array not be empty when the type is an embedded schema? This code will throw an errors that the embedded schema is not a valid type:

function someSetter = function(val) {
    // Do something on set
    return val; 
};

var parentSchema = new Schema({
    children: [{type: childSchema, set: someSetter, required: true}]
});
4

2 回答 2

1

一种解决方案是在 Schema 实例化之后设置 setter。

parentSchema.path('children').set(someSetter);
于 2013-08-27T20:25:25.003 回答
1

你可以做:

var parentSchema = new Schema({
    children: [{type: {childSchema}, set: someSetter, required: true}]
});
于 2020-12-14T13:42:21.423 回答