Search code examples
mongodbmongoosemongodb-querymongoose-schema

How to get specific field from DB query?


I'm trying to query my DB for only the dateFormatted field, sorted by the timestamp field, but the query returns all of the fields not just dateFormatted:

    const allUsersFiles = await db.FileMetadata.find({
        username: username
    }).select('dateFormatted').sort({
        timestamp: 'desc'
    });

mongoose 5.10.11 What am I doing wrong?


Solution

  • you'll have to do something like this,

    await db.FileMetadata.find({
         username: username
    }).select({'dateFormatted':1}).sort({timestamp: 'desc'});
    

    Also, _id will be returned by default. If you want to skip the keys, assign them value 0.