Reputation: 419
Ok so I have a pretty simple DB setup in a MEAN app (node, mongoose, mongo) where I have Book records, and User records. A book has a single Owner, and can have any number of shared users which are stored in an array in a field called sharedWith:. Originally I was storing the user records with an email address as the _id field. I now realize this was a dumb move on my part because if someone wants to change their email address it effectively cuts them off from their books.
The app is not live yet, so it's not a fatal mistake.
My question is, once I revert the User documents to using the original hash value for _id, and store those in the Owner and sharedWith fields in the book documents, will I have to query each hash just to retrieve the actual usable user data?
I know mongoose has a .populate() method which will resolve sub documents, but as for inserting them? Will I POST the users as email addresses, then query each and store the resulting hashes? I can do this manually, but I wanted to make sure there is not some secret mongo-sauce that can do this in the DB itself.
Thanks!
Upvotes: 0
Views: 55
Reputation: 3744
If you have the _id
available in the frontend for the user
. You can directly share him a book by adding the _id
to the sharedWith
array of a book. But if you don't have the _id
of the user available in the frontend, you need to manually get the _id
by querying with the email
and then store the _id
in the sharedWith
. As to retrieve the books, populate
is indeed the best option to use to get user data.
And to get all books shared with a user
you can do something like this,
Book.find({sharedWith:user1._id},function(err,docs){ });
This query can be made efficient if you use an index
on sharedWith
but that depends on your use case.
Upvotes: 2