Nested models mongoose with nodejs generates duplicates

here is my code for models.js where I keep models

var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var GroupSchema = new Schema({
    title      : String
    , elements   : [ElementSchema]
    , author     : String 
});
var ElementSchema = new Schema({
    date_added : Date
    , text       : String
    , author     : String 
});
mongoose.model('Group', GroupSchema);
exports.Group = function(db) {return db.model('Group');};

mongoose.model('Element', ElementSchema);
exports.Element = function(db) { return db.model('Element');
};

To me it looks pretty clear, but when I do

function post_element(req, res, next) {
Group.findOne({_id: req.body.group}, function(err, group) {
    new_element = new Element({author: req.body.author,
        date_added: new Date()});
        new_element.save();
        group.elements.push(new_element);
        group.save();
    res.send(new_element);
    return next();
})
}

I don't understand why when I go in Mongo I have two collections one called Groups with nested groups (so it looks fine) and the other collection is called Elements.

Why? Shouldn't it be called just Group ? I don't understand, a good chap that please explain it to me?

Thanks, g

When you execute this line:

new_element.save();

you're saving the newly created element to the Elements collection. Don't call save on the element and I think you'll get the behavior you're looking for.

Its because of the following line:

mongoose.model('Element', ElementSchema);

This registers a model in mongoose and when you register a model, it will create its own collection inside mongo. All you have to do is get rid of this line and you will see it disappear.

On another note, its much cleaner and easier to setup your files to only export one model per file using the following to export the model:

module.exports = mongoose.model('Group', GroupSchema);

Hope this helps!