MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Mongoose / mongodb ha accesso ai riferimenti agli oggetti nello schema durante l'aggregazione?

non c'è modo di accedere ai dati di riferimento dell'oggetto durante il Processo aggregato, il lavoro che ho impiegato per il mio progetto era aggiungere un riferimento al proprietario negli schemi in questione.

User = new Schema({
    places:[{type: Schema.Types.ObjectId, ref:'Place'}],
    shouts:[{type: Schema.Types.ObjectId, ref:'Shout'}]
});
Place = new Schema({
    owner:{type: Schema.Types.ObjectId, ref:'Place'},
    name:String,
    description:String,
});
Shout = new Schema({
    owner:{type: Schema.Types.ObjectId, ref:'Place'},
    content:String,
});

E quindi impiegato per aggregare direttamente sul documento secondario per ottenere gli utenti unici che possiedono le istanze di place, in questo modo posso ottenere un risultato shout che corrisponde a una query e a un luogo.

Esempio:

module.exports.askForShoutInPlace = function(req, res){
var pname = new RegExp(req.params.pname, 'i'); 
var stringQ = new RegExp(req.paramos.qcontent, 'i');
Place.aggregate(
    [
       //find Places that match criteria
       {'$match':{'name':pname}},
       //select owner id object to result
       {'$project':{ owner:'$owner'}},
       //group those results to single array with unique ids of users
       {'$group':{_id:'$owner'}}
    ]).exec(function(err, results){
    //find user shouts that match string and belong to owners know to be owners of a place
    Shout.find({'content':stringQ}).where({'owner':{'$in':results}}).exec(function(err, shouts){
       res.send(shouts);
    });
});

}

questo è solo il modo in cui ho scoperto di ovviare alle mie esigenze particolari, spero che possa aiutare qualcuno.