How to retrieve data with Foreign key like constraint in mongoose?

Viewed 197

I am using mongoose to interact with MongoDB. I have created two schemas. One schema has reference of another schema -

const UserSchema: Schema = new Schema({
    firstName: String,
    lastName: String,
    username: {
        type: String,
        unique: true,
        required: true,
        lowercase: true
    },
    password: {
        type: String,
        required: true
    }

});

const ArticleSchema: Schema = new Schema({
    title: {type: String, required: true},
    dateOfCreation: {type: Date, required: true},
    dateOfModification: {type: Date, required: true},
    content: {type: String, required: true},
    author: { 
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
});

There are two collections in my DB, User and Articles. TheArticleSchema has reference of the UserSchema. I want search the Articles written by a particular author's username. I have read about the populate method of mongoose but I don't know how to use the method for combined search. How can I search for the articles with by an author's username?

0 Answers
Related