【问题标题】:Nodejs mongoose sub sub document searchNodejs mongoose子子文档搜索
【发布时间】:2019-03-29 16:37:58
【问题描述】:

我有类似的架构

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 可能为空,如果城市 id 不为空,我只需要在 propertiesSchema 上搜索城市。请帮助解决这个问题。谢谢你。。

【问题讨论】:

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


    【解决方案1】:

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

    "address.city"

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

    更新

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

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

    【讨论】:

    • 但是当我尝试这个 UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ city: '5c8f7f178dec7c20f4783c0d' }" at path "address" for model "Properties"
    • 但即使现在它返回空数组而不返回过滤数组
    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2013-03-30
    • 2015-05-25
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多