node.js - Mongo/Mongoose: cleanup orphaned refs -
suppose typical one-to-many relationship modeled using references suggested mongodb official documentation:
var user = mongoose.schema({ }); var group = mongoose.schema({ user: [{ type: mongoose.schema.types.objectid, ref: 'user' }] });
let's assume care order, in users appear in group, array necessary.
now, let's assume user has been deleted -- , groups have not been maintained $pull
reason. if use mongoose's populate
looks fine, garbage persists in array.
is there way identify orphaned refs , remove them? maybe automatically -- cascade
in relational world? what's best approach maintain referential integrity in mongo/mongoose? finally, what's efficient one?
first, use remove
hook on user model try maintain data integrity on ongoing basis: user.post('remove', pulluserfromgroups);
keep integrity intact. can remove user every group single $pull
operation. mongo analog cascade
relational dbs.
for after-the fact cleanup need iterate on every group, find every userid in group.user
, query see if record exists, , pull out if not. it's simplest 1 @ time, use user.find({_id: {$in: group.user}})
, calculate user ids not found , pull them way.
Comments
Post a Comment