node.js - Individual nested subdocument Mongoose -


i'm trying embed subdocument main document,like this:

this 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 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 insert new user document 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 this:

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

the problem don't know if i'm doing correctly sintax of embed document because insert doesn't return error alerts object doesn't appear inserted new document.

what wrong?

you doing wrong. need first save alert document , use id in user document.

let alertdoc = await new alert({push: "true", email:"false", sms: "false"}).save();  // use id in user doc await new user({name: userdata.name,alerts: alertdoc._id }).save() 

in case want embed whole document instead of storing ref. modify schema of user model. define schema this.

var alertsschema  = new schema({     push:               {type: string, default: "true"},     email:              {type: string, default: "false"},     sms:                {type: string, default: "false"} }); ....  var userschema = new schema({     name:        { type: string }       created:     { type: date, default: date.now()},     alerts:      alertsschema,     documents:   [{type: schema.objectid,ref: 'document'}], }); ....  // should work var user = new user({     name: "<some name>",     alerts: {push: "true", email:"false", sms: "false"} }); 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -