pushing JSON document in subdocument inserts only ObjectId pushing JSON document in subdocument inserts only ObjectId mongoose mongoose

pushing JSON document in subdocument inserts only ObjectId


You can try another approach. First find the object, add the new Transaction to the object, and save it.

UserWallet.findOneAndUpdate({ userid: mongoose.Types.ObjectId(req.user.id)}, function(err, userWallet) {    userWallet.Transactions.push(newRecord);    userWallet.save();});


Your approach in terms of saving is okay. If you check your schema, what you are saving is an ObjectId and not necessarily an actual object.

If you want to save objects of type User instead, then you can put the actual User Model in your UserWallet scheme declaration.

However, the approach I would recommend for your situation is to keep things just the way they are and use population when retrieving userWallets.

Example:

UserWallet.find().populate('user_id').exec(function(err,userWallets){});

Now the user_id field of UserWallet will have the actual user object that is being referenced with the ObjectId. You can read more about population in the documentation