How to query document by ref field other than ref id?

Viewed 76

Hi so I have these two schemas, posts and authors where authors have a reference in posts schema. Now I want to query a post based on an author name but I'm unable to do so. I have checked and tried solutions here but nothing seems to be working.

Here's how the posts schema looks like:

const postSchema = new mongoose.Schema( {
    description: {
        type: String,
        required: true,
    }
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Author'
    }
});

module.exports = mongoose.model( 'Post', postSchema );
const authorSchema = new mongoose.Schema( {
    authorName: {
        type: String
    }
});

module.exports = mongoose.model( 'Author', authorSchema );

I can query a post by author id but I wanted to query a post based on author name, like this:

const post = await Post.find({ author: 'Dan Brown' }).populate( 'author' );

How can I do that?

UPDATE----------------------- Sample data in db:

POSTS:

{
    "_id" : ObjectId("616daf7a27b26b2a0b5431d3"),
    "post" : "What does love look like? It has the hands to help others. It has the feet to hasten to the poor and needy.",
    "postSlug" : "what-does-love-look-like-it-has-the-hands-to-help-others-it-has-the-feet-to-hasten-to-the-poor-and-needy-it-has-eyes",
    "author" : ObjectId("616d85cbdbb5874ccb62e83e"),
    "category" : [],
    "__v" : 0,
    "createdAt" : ISODate("2021-10-18T17:31:44.630Z"),
    "updatedAt" : ISODate("2021-10-18T17:31:44.630Z")
}
{
    "_id" : ObjectId("616daf7a27b26b2a0b5431e2"),
    "post" : "People always ask me, What is it that you regret? And I say, nothing, because I could not buy what I've learned",
    "postSlug": "people-always-ask-me-what-is-it-that-you-regret-and-i-say-nothing-because-i-could-not-buy-what-ive-learned-and-i-apply",
    "author": ObjectId("616d85cbdbb5874ccb62e8f5"),
    "category": [],
    "__v": 0,
    "createdAt": ISODate("2021-10-18T17:31:44.632Z"),
    "updatedAt": ISODate("2021-10-18T17:31:44.632Z")
}

{
    "_id": new ObjectId("616d85cbdbb5874ccb62e83e"),
    "authorName": "Saint Augustine",
    "authorSlug": "saint-augustine",
    "__v": 0
}

{
    "_id": new ObjectId("616d85cbdbb5874ccb62e8f5"),
    "authorName": "Dan Brown",
    "authorSlug": "dan-brown",
    "__v": 0
}
0 Answers
Related