簡體   English   中英

Nodejs mongoose子子文檔搜索

[英]Nodejs mongoose sub sub document search

我有架構之類的

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。 請幫忙解決這個問題。 謝謝..

由於city是嵌套對象,因此您可以查詢

"address.city"

Eg: 

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

UPDATE

'5c8f7f178dec7c20f4783c0d'是一個字符串。 你應該用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM