You need to enable JavaScript to run this app. 基于Mongoose的列表API无法返回address、latitude、longitude字段问题求助
优惠活动
大模型
产品
解决方案
定价
更多

基于Mongoose的列表API无法返回address、latitude、longitude字段问题求助

接口返回缺失address、latitude、longitude字段问题
  • 运行结果参考:此处粘贴对应截图
  • 实际数据参考:对应实际业务数据截图

关联代码片段

Mongoose用户Schema定义

const UserScheme = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: false
    },
    email: {
        type: String,
        unique: true,
        required: true,
        lowercase: true
    },
    address: {
        type: String,
        required: false,
        select: false
    },
    latitude: {
        type: Number,
        required: false,
        select: false
    },
    longitude: {
        type: Number,
        required: false,
        select: false
    },
    createdAt: {
        type: Date,
        default: Date.now,
    },
})

pre-save 中间件

UserScheme.pre('save', async function(next){
    const hash = await bcrypt.hash(this.password, 10)
    this.password = hash

地理编码处理逻辑

const code = await geocoder.geocode(this.address)
console.log(this.address)
console.log(code)

经纬度赋值逻辑

if(Array.isArray(code) && code[0]){
    this.latitude = code[0].latitude
    this.longitude = code[0].longitude
}

列表查询接口

router.get('/list', async (req, res) => {
    try {
        const users = await user.find()
        return res.send({users})
    } catch(err) {
        console.log(err)
        return res.status(400).send({error: 'Error listing project'})
    }
})

问题表现

调用列表查询接口时,返回结果中未包含address、latitude、longitude三个字段。

问题根因

三个缺失字段在Schema定义中均配置了select: false属性。
Mongoose的select字段配置用于控制查询返回行为:当字段设置select: false时,所有默认查询(包括当前使用的user.find())都会自动过滤该字段,无论数据库中是否存储了对应值,都不会随结果返回。

解决方案

可根据业务需求二选一:

  1. 若需要在默认查询中返回这三个字段,直接删除Schema中对应字段的select: false配置即可。
  2. 若需要保留select: false配置(比如字段属于敏感信息,默认不对外暴露),可在具体查询时手动指定需要拉取的字段:
    // 链式调用select方法,指定需要返回的默认被排除字段
    const users = await user.find().select('+address +latitude +longitude')
    

内容的提问来源于stack exchange,提问作者Paulo Avila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.09 23:54:05