Forked from arahmanali/mongoose-ref-model-service.js
Created
January 19, 2018 01:03
-
-
Save elberthcabrales/aeb58def581f2ba4857a96eb6d228366 to your computer and use it in GitHub Desktop.
Mongoose nested query on Model by field by its referenced model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Find all companies that people with lastname "Robertson" have founded | |
*/ | |
var mongoose = require('mongoose'); | |
var PersonSchema = new mongoose.Schema { | |
firstname: String, | |
lastname: String | |
}; | |
var Person = mongoose.model('Person', PersonSchema); | |
// company has a reference to Person | |
var CompanySchema = new mongoose.Schema { | |
name: String, | |
founder: { type:Schema.ObjectId, ref: 'Person' } | |
}; | |
var Company = mongoose.model('Company', CompanySchema); | |
// Get the _ids of people with the last name of Robertson. | |
Person.find({lastname: 'Robertson'}, {_id: 1}, function(err, docs) { | |
// Map the docs into an array of just the _ids | |
var ids = docs.map(function(doc) { return doc._id; }); | |
// Get the companies whose founders are in that set. | |
Company.find({founder: {$in: ids}}, function(err, docs) { | |
// docs contains your answer | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment