Node.js猫鼬子子文档搜索

时间:2019-03-23 07:19:34

标签: node.js mongoose mongoose-schema mongoose-populate nodejs-server

我有类似

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

和类似的地址模式

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

,我想从propertiesSchema中搜索城市,我使用mongoose作为mongodb。我也有可选的searchData对象,例如

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

此处城市ID可能为null,而我需要,如果城市ID不为null,则只需要在propertiesSchema上搜索城市。请帮助解决此问题。谢谢。。

1 个答案:

答案 0 :(得分:0)

city是一个嵌套对象,您可以像

一样查询

"address.city"

Eg: 

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

更新

'5c8f7f178dec7c20f4783c0d'是一个字符串。您应该使用

const mongoose = require('mongoose');
mongoose.Types.ObjectId('5c8f7f178dec7c20f4783c0d');