node.js - One-To-One relationship with mongoose? -
i aware of how set 1 many relationship between mongoose entities, following type of code :
friends: [{type: objectid, ref: 'user'}] but if want have one-to-one relationship - such client user related to?
first of all, there huge difference between relationships in mongodb , in sql based datastores (you need clear get-go).
relationships in mongodb representations of related data. there no mechanism maintains integrity of these relationships.
what mongoose refs use field having ref option query _id field of documents in referenced collection. used operations populate (which internally calls findbyid queries on target collection , replaces referenced field documents).
this being cleared, can store 1 or many ids referenced collection in field, creating one-to-one or one-to-many "relationships".
so, store single id referenced collection, syntax be:
client: {type: mongoose.schema.types.objectid, ref: 'client'} //no arrays, want store single id only. in same way, can store many ids referenced collection so:
friends: [{type: mongoose.schema.types.objectid, ref: 'user'}] //the array stores multiple ids, creating one-to-many "relationship" edit:
make sure have required mongoose module @ beginning.
var mongoose = require('mongoose');
Comments
Post a Comment