Nodejs mongoose子子文档搜索

问题描述 投票:0回答:1

我有架构之类的

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上搜索city。请帮忙解决这个问题。谢谢..

node.js mongoose mongoose-schema mongoose-populate nodejs-server
1个回答
0
投票

由于city是一个嵌套对象,你可以像查询一样

"address.city"

Eg: 

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

UPDATE

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

const mongoose = require('mongoose');
mongoose.Types.ObjectId('5c8f7f178dec7c20f4783c0d');
© www.soinside.com 2019 - 2024. All rights reserved.