Home > database >  MongoDB - How to get content from a specific field only
MongoDB - How to get content from a specific field only

Time:05-24

What is the best way to retrieve the content from specific fields only in Mongo?

Using Mongoose, here is my Schema:

module.exports = mongoose => {
    const Shop = mongoose.model(
        'Shop',
        mongoose.Schema(
            {
                    cid: String,
                    title: String,
                    categoryName: String,
                    address: {
                        street: String,
                        city: String,
                        postalCode: Number,
                        country: String,
                        fullAddress: String,
                    },
                    website: String,
                    phone: String,
                    location: {
                        lat: Number,
                        lng: Number,
                    },
                    totalScore: Number,
                    reviewsCount: Number,
                    openingHours: [
                        {
                            day: String,
                            hours: String,
                        }
                    ],
                    imageUrls: [{type: String}],
                    reviews: [
                        {
                            name: String,
                            text: String,
                            publishedAtDate: String,
                            stars: Number,
                            id: String,
                        }
                    ],
                }
        )
    )
    return Shop;
}

I'm looking for a Mongoose query returning the cities only, for instance.

Here is the function I tried, but I cannot make it working...

const db = require('../models');
const Shop = db.shop;

const readCities = async(req, res) => {
    try {

        const cities = Shop.find({}).select('address.city');

        console.log(cities);

        res
            .status(200)
            .send(cities);

    } catch (error) {
        console.log('Error occured while retrieving cities... ', error);
        res
            .status(500)
            .send(error);
    }
}

EDIT

As suggested, when I'm running the following updated script:

const readCities = async(req, res) => {
    try {

        const cities = Shop.find({}, { 'address.city' : 1});

        console.log(cities);

        res
            .status(200)
            .send('It works');
    } catch (error) {
        console.log('Error occurred while retrieving cities... ', error);
        res
            .status(500)
            .send(error);
    }
}

this is the answer I get:

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    modelName: 'Shop',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: {},
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'shops',
    collectionName: 'shops',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: undefined,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://192.168.1.211:27019/seox',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      db: [Db],
      host: '192.168.1.211',
      port: 27019,
      name: 'seox'
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { Shop },
  schema: Schema {
    obj: {
      cid: [Function: String],
      title: [Function: String],
      categoryName: [Function: String],
      address: [Object],
      website: [Function: String],
      phone: [Function: String],
      location: [Object],
      totalScore: [Function: Number],
      reviewsCount: [Function: Number],
      openingHours: [Array],
      imageUrls: [Array],
      reviews: [Array]
    },
    paths: {
      cid: [SchemaString],
      title: [SchemaString],
      categoryName: [SchemaString],
      'address.street': [SchemaString],
      'address.city': [SchemaString],
      'address.postalCode': [SchemaNumber],
      'address.country': [SchemaString],
      'address.fullAddress': [SchemaString],
      website: [SchemaString],
      phone: [SchemaString],
      'location.lat': [SchemaNumber],
      'location.lng': [SchemaNumber],
      totalScore: [SchemaNumber],
      reviewsCount: [SchemaNumber],
      openingHours: [DocumentArrayPath],
      imageUrls: [SchemaArray],
      reviews: [DocumentArrayPath],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {
      'openingHours.day': [SchemaString],
      'openingHours.hours': [SchemaString],
      'openingHours._id': [ObjectId],
      'imageUrls.$': [SchemaString],
      'reviews.name': [SchemaString],
      'reviews.text': [SchemaString],
      'reviews.publishedAtDate': [SchemaString],
      'reviews.stars': [SchemaNumber],
      'reviews.id': [SchemaString],
      'reviews._id': [ObjectId]
    },
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: { address: true, location: true },
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      cid: [Function: String],
      title: [Function: String],
      categoryName: [Function: String],
      address: [Object],
      website: [Function: String],
      phone: [Function: String],
      location: [Object],
      totalScore: [Function: Number],
      reviewsCount: [Function: Number],
      openingHours: [Array],
      imageUrls: [Array],
      reviews: [Array],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [ [Object], [Object] ],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true
  },
  op: 'find',
  options: {},
  _conditions: {},
  _fields: { 'address.city': 1 },
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: [Collection],
      Promise: [Function: Promise],
      modelName: 'Shop',
      _closed: false,
      opts: [Object],
      name: 'shops',
      collectionName: 'shops',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'shops'
  },
  _traceFunction: undefined,
  '$useProjection': true,
  _userProvidedFields: { 'address.city': 1 }
}

How can I use the results ? i.e. where are the data ?

CodePudding user response:

try this code :

const readCities = async(req, res) => {
    try {

        const cities = await Shop.find({}, { 'address.city' : 1});

        console.log(cities);

        res
            .status(200)
            .send('It works');
    } catch (error) {
        console.log('Error occurred while retrieving cities... ', error);
        res
            .status(500)
            .send(error);
    }
}
  • Related