json - Inserting elements in array mongoose creates Object in NodeJS -
i'm trying insert documents in array using mongoose.
here's schema:
var user = new mongo.schema({ _id : number, devices:[ { device_id : string, type : string } ]})
the update code in nodejs looks like:
app.put('/user/update',function(req,res){ var obj = req.body; users.update( {'user.username' : obj.email}, { 'user.username' : obj.email, 'user.password' : obj.password, 'user.name.first' : obj.name, 'user.department' : obj.department, 'user.year' : obj.year, 'user.college' : obj.college, 'user.contact.phone': obj.contact, 'user.last_login' : obj.last_login, $push:{ 'devices': { device_id: 'sadasd32u4je3bdjas', type: 'windows' } } }, function(err){ if(err) res.json({"foo": string(err)}); else res.json({"foo": "successfully signed up!"}); }); } );
but instead inserts like:
"devices": [ "[object object]", "[object object]", "[object object]", "[object object]", "[object object]" ],
where did go wrong? again.
use findoneandupdate()
method 'upsert' option set true - creates object if doesn't exist (defaults false):
var obj = req.body; var query = {'user.username': obj.email}; var doc = { $set: { 'user.username': obj.email, 'user.password': obj.password, 'user.name.first': obj.name, 'user.department': obj.department, 'user.year': obj.year, 'user.college': obj.college, 'user.contact.phone': obj.contact, 'user.last_login': obj.last_login }, $push: { 'devices': { device_id: 'sadasd32u4je3bdjas', type: 'windows' } } }; var options = {upsert: true}; users.findoneandupdate(query, doc, options, function(err){ if(err) res.json({"foo": string(err)}); else res.json({"foo": "successfully signed up!"}); });
Comments
Post a Comment