node.js - Express: Embed document in the existing document -
i developing application in express
, node
, mongo
being database. have collection users
, , user
can have mutiple registered-ids
. one-to-many
relationship. m trying embed document
in user collection this:
post(function (req, res, next) { var pid=req.body.pid; var sid=req.body.sid; var rfname=req.body.rfname; var des=req.body.des; var brand=req.body.brand; var model=req.body.model; var serial=req.body.serial; var location=req.body.location; var arr={pid: 'pid', sid: 'sid', rfname: 'rfname' ,des: 'des', brand: 'brand', model: 'model' ,serial: 'serial', location: 'location'}; mongoose.model('user').findone({'pemail': req.session.email}, function (err, user){ if(err){ } else { user.registeredid = arr; user.save(function(err){ if(err){ } else { res.render('user/register', {'success': 'dfhlaksdhfh'}); } }) } }); }
my user schema this:
var mongoose = require('mongoose'); var userschema = new mongoose.schema({ email: string, password: string, fname: string, lname: string, plang: string, slang: string, country: string, state: string, city: string, postalcode: string, address1: string, address2: string, pemail: string, semail: string, age: string, gender: string, pphone: string, sphone: string, q1: string, a1: string, q2: string, a2: string, cfname: string, clname: string, cemail: string }); mongoose.model('user', userschema);
guide me, doing wrong, because not embed document in existing document. need define in schema, if so, how?
in schema definition, field registeredid
not defined , default through strict option, mongoose ensures values passed model constructor not specified in our schema not saved db, hence not creating modified document.
you can either explicitly define field in schema or set strict option false in schema definition:
// set false.. var userschema = new schema({..}, { strict: false });
and implement 1 of findandmodify()
methods findoneandupdate()
update user document pushing new object new array field registeredid
. re-write post function as:
post(function (req, res, next) { var user = mongoose.model('user'), pid=req.body.pid, sid=req.body.sid, rfname=req.body.rfname, des=req.body.des, brand=req.body.brand, model=req.body.model, serial=req.body.serial, location=req.body.location, arr = { 'pid': pid, 'sid': sid, 'rfname': rfname, 'des': des, 'brand': brand, 'model': model, 'serial': serial, 'location': location }, condition = { 'pemail': req.session.email }, update = { "$push": { 'registeredid': arr } }; user.findoneandupdate( condition, update, function (err, doc){ if(err){} else { // doc contains modified document res.render('user/register', {'success': 'dfhlaksdhfh'}); } } ); });
Comments
Post a Comment