0

I have schema like

const propertiesSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    shortDescription: String,
    totalArea: String,
    address: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Address",
        required: true
    }
})

and the address schema like this

const addressSchema = new Schema({
    addressLine1: {
        type:String,
        required:false
    },
    addressLine2: {
        type:String,
        required:false
    },
    city:{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:"City"
    }
})

and i want to search city from propertiesSchema am using mongoose for the mongodb. and also i have optional searchData object like

searchData = {
    "name":"test"
    "city":"5c8f7f178dec7c20f4783c0d"
}

here the city id may be null and i need if the city id not null then only need to search city on propertiesSchema . please help to solve this problem. thank you..

sooraj
  • 1

1 Answers1

0

As city is an nested object you can query that like

"address.city"

Eg: 

searchData = {
    "name":"test"
    "address.city":"5c8f7f178dec7c20f4783c0d"
}

UPDATE

'5c8f7f178dec7c20f4783c0d' is a string. You should use

const mongoose = require('mongoose');
mongoose.Types.ObjectId('5c8f7f178dec7c20f4783c0d');
Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
  • but i get the error when i trying this UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ city: '5c8f7f178dec7c20f4783c0d' }" at path "address" for model "Properties" – sooraj Mar 29 '19 at 05:43
  • but even now its return the empty array not returning the filtered array – sooraj Mar 29 '19 at 12:07