What I'm trying to accomplish is to have an Array of Objects (the subdocument way: defined in a Schema) inside a main document, and I want this subdocument to behave as a document itself.
This is, when pushing an Object into the Subdocument Array, I would like that it threw an error:
- if any of the
unique
fields of the object being inserted are already taken - if the object being inserted doesn't match the
TemplateSchema
This would be my main document:
var ApplicationSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
description: {
type: String
},
...
templates: {
type: [TemplateSchema]
}
});
and the following would be the subdocument, the templates
field inside the ApplicationSchema
:
var TemplateSchema = mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
sparse: true
},
description: {
type: String
},
...
});
In this case, when I am trying to:
- add a new object with an already existing
name
, or - push any trash into my subdocument
it's happening that:
- no error is being thrown about the duplicated field value
- the trash object (i.e.
{some: "trash"}
) is being inserted - not really the object itself, but it's pushing an emptytemplate
object inside thetemplates
array
and I can't figure out why.
Here is the query I'm using to insert new template objects into the templates
array inside the main document, which I guess is here where it is not working as expected:
exports.create = function(id, objTemplate, callback) {
ApplicationModel.findByIdAndUpdate(
{ _id: id },
{
$push: {
"templates": objTemplate
}
},
{
safe: true,
upsert: true,
new : true
},
function(err, application) {
// handle stuff
}
);
};