Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mitchellporter/865f71138f22770b0ea16a532d0c604e to your computer and use it in GitHub Desktop.
Save mitchellporter/865f71138f22770b0ea16a532d0c604e to your computer and use it in GitHub Desktop.
Finding a thing by reference using a non ID field.
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