Reputation: 9830
Is it possible to reference 2 documents to each other using ref
and if it is possible, is it recommended and is it good practice ? Like this :
FirstDocumentId Collection's Model :
const FirstDocumentId = mongoose.model(
'FirstDocumentId',
new mongoose.Schema({
coolField: String,
secondDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'secondDocumentId'}
})
);
SecondDocumentId Collection's Model :
const SecondDocumentId = mongoose.model(
'SecondDocumentId',
new mongoose.Schema({
someField: String,
firstDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'firstDocumentId'}
})
);
The point of this is to create a 1 to 1 relationship and being able to access both documents easily.
I know I can just reference 1, without referencing the second to the first, but I thought it would be simpler to modify them both.
Upvotes: 2
Views: 3464
Reputation: 17915
Yes you can reference a collection to another collection like the way you're doing, ideally that's how relationships between two collections are maintained in MongoDB, but you need to understand as MongoDB is schema free, there is no direct way to create/update/delete documents in second collection by creating/updating/deleting relative documents in first collection(Collections & their docs are independent - operations are atomic at document level). As there is no direct way - You've to write application logic or some kind of batch job or MongoDB-stitch to achieve reference maintainance.
$lookup
is a helpful operator - So by using that you doesn't need to mention ref for those fields. If you're using mongo shell or any client like robo3T or mongo compass or any native driver like mongodb driver for node.js you can use native $lookup
. Even you can use lookup while using mongoose but mongoose claims they've .populate() which is very powerful compared to native $lookup
, to use that you'll use ref
. Apart from that there is no use of it, Even having the same models you can use $lookup
with mongoose instead of using populate._id
fields, you can actually reference any field but the values & types should match in both of the collections, that way it could be easy while querying else you need to convert one to another while querying every time, So be careful on writes.Upvotes: 1