javascript - Mongoose update subdocument of subdocument -
my schema definition below. userschema has embedded cards in turn has many transactions..
var transactionschema = new schema({ merchantname: string, transactiontime: date, latitude: number, longitude: number, amount: number }); var cardschema = new schema({ cardissuer: string, lastfour: string, expirationdate: string, transactions : [transactionschema] }); /* * ...user schema... */ var userschema = new schema({ name: string, email: { type: string, lowercase: true }, role: { type: string, default: 'user' }, hashedpassword: string, provider: string, salt: string, imageurl: string, phonenumber: string, card: [cardschema] });
i want add transaction card in userschema not sure how in mongoose / mongodb
i identify user , card follows..
the api call goes through auth middleware first
function isauthenticated() { return compose() // validate jwt .use(function(req, res, next) { // allow access_token passed through query parameter if(req.query && req.query.hasownproperty('access_token')) { req.headers.authorization = 'bearer ' + req.query.access_token; } validatejwt(req, res, next); }) // attach user request .use(function(req, res, next) { user.findbyid(req.user._id, function (err, user) { if (err) return next(err); if (!user) return res.send(401); req.user = user; next(); }); }); } // update based on neil's answer below... exports.create = function(req, res) { //var useritem = req.user; //console.log(useritem._id); //console.log(req.params.card); transaction.create(req.body, function(err, transaction){ console.log(transaction); //id = mongoose.types.objectid; user.findoneandupdate({"card._id":id(req.params.card)},{ // $set : { // role: 'user1' // } ---- update operation works!! "$push": { "card.$.transactions": transaction } // -- update operation causes error ... }, function(err,user) { // updated document here console.log('err' + err + " user " + user) ; return res.json(200, user); } ) // } // }) }) };
adding new elements inner array not difficult, need match position of outer array update in query , apply positional $
operator in update portion.
var transaction; // , initialize new transaction user.findoneandupdate( { "card._id": cardid }, { "$push": { "card.$.transactions": transaction.toobject() } }, function(err,user) { // updated document here } )
so straightforward $push
operations. careful ever want $push
or $pull
trying update @ position of in "inner" array not possible since positional operator contain first match, or position in "outer" array.
Comments
Post a Comment