Friday 14 April 2017

Individual nested subdocument Mongoose

I'm Trying to embed a subdocument into my main document,like this:

This is the main document.js

var mongoose = require('../../db/mongodb.connector'),
    Schema   = mongoose.Schema;

require('./document.model');
var Document= mongoose.model('Document');
require('./alert.model');
var Alert = mongoose.model('Alert');

    var userSchema = new Schema({
        name:        { type: String }  
        created:     { type: Date, default: Date.now()},
        alerts:      {type: Schema.ObjectId,ref: 'Alert'},
        documents:   [{type: Schema.ObjectId,ref: 'Document'}],

    });

module.exports = mongoose.model('User', userSchema);

This is the embed document.js

var mongoose = require('../../db/mongodb.connector'),
    Schema   = mongoose.Schema;


var alertsSchema  = new Schema({
    push:               {type: String, default: "true"},
    email:              {type: String, default: "false"},
    sms:                {type: String, default: "false"}
});

module.exports = mongoose.model('Alert', alertsSchema);

When I Insert a new User document like this:

exports.insertUser = function (userData, res) {

        var user = new User({
            name: userData.name,
            alerts: {push: "true", email:"false", sms: "false"}

        });

        user.save...

...

The returned data is this:

{ name: 'name',
  documents: [],
  created: 2017-04-14T10:22:05.612Z
}

The problem is that I don't know if I'm doing correctly the sintax of embed document because the insert doesn't return any error but the alerts object doesn't appear into the inserted new document.

What would be wrong?



via Hanzo

No comments:

Post a Comment