gb_spectrum
gb_spectrum

Reputation: 2301

Mongoose - inserting subdocuments

I have a user model, and a log model. The log model is a subdocument of user model. So in my user model I have:

var mongoose = require('mongoose');
var Log = require('../models/log');

var UserSchema = new mongoose.Schema({
username: {
    type: String,
    unique: true
},
logsHeld: [
    Log
]
});

Then in my 'Log' model I have:

var mongoose = require('mongoose');
var logSchema = new mongoose.Schema({
    logComment: {
        type: String,
    },
});

module.exports = mongoose.model('Log', logSchema);

So upon creation of a 'user', the 'logsHeld' always begins empty. I want to know how to add subdocuments to this user model.

I've tried doing this POST method:

router.post('/createNewLog', function(req, res) {
    var user = new User ({
            logssHeld: [{
                logComment: req.body.logComment
            }]
        });
            user.save(function(err) {
                if(err) {
                req.flash('error', 'Log was not added due to error');
                return res.redirect('/home');
            } else {
                req.flash('success', 'Log was successfully added!');
                return res.redirect('/home');
            }
        });
    });

But this doesn't work. It also includes a 'new User' line, which I don't think I need given this would be for an existing user.

Upvotes: 1

Views: 2721

Answers (3)

chridam
chridam

Reputation: 103455

You need to use the logSchema instead of the Log model as your subdocument schema in User model. You can access the schema as follows:

var mongoose = require('mongoose');
/* access the Log schema via its Model.schema property */
var LogSchema = require('../models/log').schema; // <-- access the schema with this 

var UserSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true
    },
    logsHeld: [LogSchema]
});

Picking up from your comments in another answer where you are facing another issue

WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: testDB.users.$email_1 dup key:

you are getting this because there's already a document in your users collection that has most probably a null value on the email field. Even though your schema does not explicitly specify an email field, you may have an existing old and unused unique index on users.email.

You can confirm this with

testDB.users.getIndexes() 

If that is the case and manually remove the unwanted index with

testDB.users.dropIndex(<index_name_as_specified_above>)

and carry on with the POST to see if that has rectified the error, I bet my $0.02 that there is an old unused unique index in your users collection which is the main issue.

Upvotes: 2

bitWise515
bitWise515

Reputation: 11

Try using logSchema which references only the subdocument schema, Log refers to the entire contents of ../models/log

var UserSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true
    },
    logsHeld: [
        logSchema
    ]
});

Documentation: http://mongoosejs.com/docs/subdocs.html

Upvotes: 1

abdulbari
abdulbari

Reputation: 6242

Try push to insert item in array in mongoose

var user = new User;
 user.logssHeld.push({
    logComment: req.body.logComment
});

user.save(function(err, doc) {
    //DO whatever you want
});

see the docs here

Upvotes: 0

Related Questions