sql >> Base de Datos >  >> NoSQL >> MongoDB

Node.js:creación de relaciones con Mongoose

Parece que está buscando probar la nueva funcionalidad de llenado en Mongoose.

Usando su ejemplo anterior:

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : { type: ObjectId, ref: 'SubdomainSchema' }

El subdomain el campo se actualizará con un '_id' como:

var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()

var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()

Para obtener datos del subdomain tendrá que usar la sintaxis de consulta un poco más compleja:

CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) { 
// Your callback code where you can access subdomain directly through custPhone.subdomain.name 
})