0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

but in this case, what will be the point of having two separate schemas?
It seems that with Mongoose, if you want an array of objects in your schema, those objects have to be defined using a Schema (or be one of the built-in schema types).
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.