Last active
May 28, 2024 12:22
-
-
Save furf/5991442 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
@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.