'Use req.user instead of User.findOne when updating MongoDB sub-documents?
I am using Passport.js for Express, which already holds the current user in the session variable req.user
.
Yet when I try to update a MongoDB database I can only use req.user
to identify the current user in certain cases. In others, I have to first do a root search to identify the correct user. Why?
I'm updating a database with this structure:
User A
Stocks [array]
Notes [array]
User B
Stocks [array]
Notes [array]
User C
...
Let's say we have already populated the database with 'stocks', and with 'notes' belonging to these 'stocks'. Now the user clicks a button to delete an existing 'note'.
This code works fine:
await User.updateOne (
{ $and: [ { email: req.user.email }, { 'stocks.ticker': req.body.ticker } ]},
{ $pull: { 'stocks.$.notes': { _id: req.body.id }}}
)
This query contains both the email to identify the user, and the stock's ticker to identify the relevant stock. And then the note is pulled from that stock. As said, it works fine.
But since I already know the current user (set in Passport's req.user
variable) I don't want to have to include the email in the query and waste resources finding the current user.
I want to reduce to this:
await req.user.updateOne (
{ 'stocks.ticker': req.body.ticker },
{ $pull: { 'stocks.$.notes': { _id: req.body.id }}}
)
But this does not work, and I don't understand why.
If I use the req.user
variable for a simpler pull action, it does work. I.e. the following code works to pull a stock document from the user's database:
await req.user.updateOne (
{ $pull: { stocks: { ticker: req.body.ticker }}}
)
But if I include a query before the pull action, it does not. I have tried everything I can think of to solve this. No joy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|