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

Populate () ref anidada en una matriz de objetos

Quizás algún código, también algunas correcciones a su enfoque. Quiere un tipo de unión "manyToMany" que puede hacer de la siguiente manera:

var async =require("async"), mangosta =require("mangoose"), Schema =mangosta.Esquema;mangoose.connect('mongodb://localhost/usuario');var userSchema =new Schema({ email:String, displayName:String, suscripciones:[{ type:Schema.Types.ObjectId, ref:'UserShow' }]});userShows =new Schema({ show:{ type:Schema.Types.ObjectId, Ref:'Mostrar' }, favorito:{ tipo:booleano, predeterminado:falso }}); var showSchema =nuevo esquema ({ título:cadena, descripción general:cadena, suscriptores:[{ tipo:Schema.Types.ObjectId, ref:'Usuario' }], episodios:[{ título:Cadena, primera emisión:Fecha }]});var Usuario =mongoose.model('Usuario', userSchema);var Show =mongoose.model('Show', showSchema); var UserShow =mongoose.model('UserShow', userShows);var usuario =nuevo Usuario({ email:'[email protected]
 ', displayName:'bill'});user.save(function(err,user) { var show =new Show({ title:"Some Show", descripción general:"Un programa sobre algunas cosas". }); show. suscriptores.push( user._id ); show.save(function(err,show) { var userShow =new UserShow({ show:show._id }); user.subscriptions.push( userShow._id ); userShow.save( function(err,userShow) { user.save(function(err,user) { console.log( "done" ); User.findOne({ displayName:"bill" }) .populate("suscripciones").exec(función (err, usuario) { async.forEach (usuario. suscripciones, función (suscripción, devolución de llamada) { Show.populate (suscripción, { ruta:"mostrar"}, función (err, salida) { si (err) arrojar error; devolución de llamada (); }); }, función (err) { console.log (JSON.stringify (usuario, indefinido, 4)); }); }); }); }); });});  

Eso debería mostrar una respuesta poblada como esta:

ejemplo @sqldat.com ", "displayName":"factura", "__v":1, "suscripciones":[ { "_id":"53a7b8e60462281231f2aa1a", "show":{ "_id":"53a7b8e60462281231f2aa19", "title":"Algunos Show ", "descripción general":"Un programa sobre algunas cosas.", "__v":0, "episodios":[], "suscriptores":[ "53a7b8e60462281231f2aa18" ] }, "__v":0, "favorito":falso } ]}

O sin el "manyToMany" también funciona. Tenga en cuenta aquí que no hay una llamada inicial para completar:

var async =require("async"), mangosta =require("mangoose"), Schema =mangosta.Esquema;mangoose.connect('mongodb://localhost/usuario');var userSchema =new Schema({ email:String, displayName:String, suscripciones:[{ show:{type:Schema.Types.ObjectId, ref:'UserShow' }, favorito:{ type:Boolean, default:false } }]});var showSchema =new Schema({ title:String, descripción general:String, suscriptores:[{ type:Schema.Types.ObjectId, ref:'User' }], episodios:[{ title:String, firstAired:Date }]}); var Usuario =mongoose.model('Usuario', userSchema);var Mostrar =mongoose.model('Mostrar', showSchema);var usuario =nuevo Usuario({ email:'[email protected]
 ', displayName:'bill'});user.save(function(err,user) { var show =new Show({ title:"Some Show", descripción general:"Un programa sobre algunas cosas". }); show. suscriptores.push( usuario._id ); show.save(función(err,mostrar) { usuario.suscripciones.push({ mostrar:show._id }); usuario.save(función(err,usuario) { console.log( "hecho"); Usuario.findOne({ displayName:"factura" }).exec(función(err,usuario) { async.forEach(usuario.suscripciones,función(suscripción,devolución de llamada) { Show.populate(suscripción, { ruta :"show" }, function(err,output) { if (err) throw err; callback(); }); },function(err) { console.log(JSON.stringify(user, undefined, 4) ); }); }); }); });});