mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
222 stars 36 forks source link

Need match case #21

Closed dixitsharma closed 4 years ago

dixitsharma commented 8 years ago

I am not able to match the auto-populated data of mongoose Schema EG:->

var baseSchema=new Schema{
name:{type:String}
childSchema:[{type:String, ref:'ChildSchema' autopopulate:{ select :'name address'}}]
}
var ChildSchema=new Schema{
name:{type:String}
address:{type:String}
}
baseSchema.find({childShema.$.name='abc'});
                                OR

baseSchema.find({childShema.name='abc'}); RESULT Coming : NO-DATA Result Needed : [values]

dixitsharma commented 8 years ago

I am also working with limit too

vkarpov15 commented 8 years ago

Can you please clarify what you mean by "working with limit"? Also, can you provide a more complete code sample? The provided code sample only tangentially resembles JavaScript...

eliasjnior commented 4 years ago

Can you please clarify what you mean by "working with limit"? Also, can you provide a more complete code sample? The provided code sample only tangentially resembles JavaScript...

@vkarpov15 I think he tried to use search in an autopopulated value. I'm almost sure he can't do that. He is trying to find with a document property value, but in schema is a reference.

Let's supose I have an User and Posts:

const userSchema = new Schema({
   username: { type: String, required: true },
});

const User = mongoose.model('User', userSchema, 'users');

const postSchema = new Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User', autopopulate: true }
});

const Post = mongoose.model('Post', postSchema);

He is trying to find all posts by some username. This won't work, would need to do:

postSchema.statics.findByUsername = function(username, callback) {
    // Store the find query
    const query = this.find();
    // Find the user id and add to where query
    User.findOne({ username: username }, function (error, user) {
        query.where({ user: user._id }.exec(callback);
    });

   return query;
}

I didn't test exactly this code, but the logic is that. It's too late, but maybe it will help somebody in future ;)

vkarpov15 commented 4 years ago

@eliasjnior I'd recommend embedding username in postSchema if you want to find posts by username. But your approach works as well.