You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按自定义User ID而非MongoDB ID查询并返回指定字段?

Node.js + Mongoose 自定义ID查询及返回字段处理问题

我正在用Node.js开发包含POST、GET、DELETE、PUT方法的REST API,使用Mongoose操作MongoDB。

我的Mongoose Schema

const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
    "id": {
        type: Number,
        require: true
    },
    "email": {
        type: String,
        require: true
    },
    "first_name":{
        type: String,
        require: true
    },
    "last_name":{
        type: String,
        require: true
    },
    "company":{
        type: String,
        require: true
    },
    "url":{
        type: String,
        require: true
    },
    "text":{
        type: String,
        require: true
    }     
});

module.exports = mongoose.model('User', userSchema);

需求说明

  • GET请求通过自定义id字段(而非MongoDB自动生成的_id)查询用户,使用端点 localhost:9000/api/user/[id]
  • 返回结果仅保留Schema中定义的字段,排除MongoDB自动添加的_id和__v字段

期望返回格式:

{
    "id": 1,
    "email": "John@gmail.com",
    "first_name": "Smith",
    "last_name": "Smith",
    "company": "google",
    "url": "Smith.com",
    "text": "John Smith"
}

不希望返回的格式:

{
    "_id": "1nf19tg427gnvn9v",
    "id": 1,
    "email": "John@gmail.com",
    "first_name": "Smith",
    "last_name": "Smith",
    "company": "google",
    "url": "Smith.com",
    "text": "John Smith",
    "__v": 1
}

现有代码及问题

最初的GET方法使用findById查询MongoDB自带的_id:

function GetUser(req, res){
    const { id } = req.params;
    userSchema
        .findById(id)
        .then((data) => res.json(data))
        .catch((error) => res.json({ msg: error }))
};

之后修改为按自定义id字段查询:

function GetUser(req, res){
    const { id } = req.params;
    userSchema
        .find({id})
        .then((data) => res.json(data))
        .catch((error) => res.json({ msg: error }))
};

现在尝试只返回first_name和id字段,使用.then((data) => res.json(data.id, data.first_name))时,Postman一直加载,没有响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:31:07