Skip to content

Instantly share code, notes, and snippets.

@furf
Last active May 28, 2024 12:22
Show Gist options
  • Save furf/5991442 to your computer and use it in GitHub Desktop.
Save furf/5991442 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');
@kitlee
Copy link

kitlee commented Nov 12, 2015

What about if user is an array (users)?

@eassymo
Copy link

eassymo commented Feb 23, 2018

This have the right idea. Thanks.

@eassymo
Copy link

eassymo commented Feb 23, 2018

@kitlee just change
var query = this.findOne();
by
var query = this.find();

And results of:
User.findByUsername(username, function (error, user) { ...
by:
User.findByUsername(username, function (error, users) { if(error){ // etc } const lstUsersIds= []; users.forEach(user => { lstUsersIds.push(user ._id); }); if (lstUsersIds.length > 0) { // _id of users query.where('_id', {$in: lstUsersIds}); } }

this basically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment