node.js - Mongoose nested query on Model by field of its referenced model -


It looks like there is a lot of Q / A on this topic on Stakeoverflow, but I do not think the exact answer is anywhere.

What do I have:

I have company and person models:

  var mongoose = require (' Mongoose '); Var PersonSchema = New Mongoose Shama {name: string, last name: string}; // The company's personality is a reference to the heroic company. Schema = new mongosse Cheema {name: string, founder: {type: schema. Object ID, ref: person}};  

What do I need:

Search for all companies whose people have their last name "Robertson" installed

< P> What I tried:

  company.find ({'founder.id': 'robertson'}, function (mistake, companies) {console.log (Companies); / / Get an empty table}}  

Then I thought the person is not embedded but is referenced, so I populated the installer to populate and Then 'rober Tried to use search with the last name of 'tasan'

  // 1. Retrieve all companies 2. 2. Populate your founders 3. 3. Populated companies Find out the last name of 'Robertson' ({}) Populate ('founder') .find ({'founder.lastname': 'robertson'}) .exec (function (mistake, companies) {console.log (companies) ); // Get an empty array again}}  

I still query the companies with the person's ID as string But it is not exactly what I want to do as you can understand

  company.find ({'founder': '525cf76f919dc8010f00000d'}, function (mistake, companies) { Console.log (companies); // this work}};  

You can not do this in a single query because MongoDB does not support joins . Instead, you have to break it in a few steps:

// Get Limits of Robertson's last name Person.find ({lastname: 'Robertson'}, {_id: 1}, function (mistake, docs) {// map just _ides var ids = docs.map {map} {map in an array of return Doc._id;}); // Companies whose installers are in that set. Company.find ({founder: {$ in: id}}, function (mistake, docs) {// your answer in docs}};}); < / Pre>

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -