Forked from furf/mongoose-find-by-reference-field.js
Created
November 8, 2021 22:25
-
-
Save IAmJakPro/f42673c6b51b243f3f0f4d77e384619f to your computer and use it in GitHub Desktop.
Finding a thing by reference using a non ID field.
This file contains 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
var mongoose = require('mongoose'), | |
// Load User model | |
User = mongoose.model('User'), | |
// Create Thing schema | |
thingSchema = new mongoose.Schema({ | |
_user: { | |
type: ObjectId, | |
ref: 'User', | |
required: true, | |
unique: true | |
} | |
}), | |
Thing; | |
/** | |
* Find a profile using the user's username | |
* @param {String} username | |
* @param {Function} callback | |
* @return {Query} | |
*/ | |
thingSchema.statics.findByUsername = function (username, callback) { | |
// Prepare the query so it can be returned | |
// before asynchronous findByUsername is complete | |
var query = this.findOne(); | |
// Find user by username | |
User.findByUsername(username, function (error, user) { | |
var scope = this; | |
var args = arguments; | |
if (error || !user) { | |
// Maintain asynchronous behavior | |
return process.nextTick(function () { | |
// Maintain scope of callback | |
callback.apply(scope, args); | |
}); | |
} | |
// Update query with user id and execute | |
query.where('_user', user._id).exec(callback); | |
}); | |
// Return query for optional modification at runtime | |
return query; | |
}; | |
Thing = mongoose.model('Thing', thingSchema); | |
// Usage | |
Thing.findByUsername('furf', function (error, thing) {}); | |
// With optional modification | |
Thing.findByUsername('furf', function (error, thing) {}).populate('_user'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment