【问题标题】:Returning specific fields with mongoose使用猫鼬返回特定字段
【发布时间】:2021-05-19 17:23:09
【问题描述】:

我正在尝试完成一些非常简单的事情,但仍然失败了。

我想做的是,当我在服务器上收到get 请求时,我想返回所有文档,但只返回填充的特定字段。

我的架构如下

var clientSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    phone:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    address: {
        type: String,
        required: false
    }
});

var orderDetailsSchema = new Schema({
    //isn't added to frontend
   confirmed:{
       type: Boolean,
       required: true,
       default: false
   },    
   service:{
       type: String,
       required: true
   },
   delivery:{
       type: String,
       required: false
   },
    payment:{
        type: String,
        required: false
    },
    status:{
        type: String,
        required: true,
        default: "new order"
    },
});

var orderSchema = new Schema({

   reference:{
       type: String,
       required: true
   },

    orderdetails: orderDetailsSchema,

    client: clientSchema,

    wheelspec: [wheelSchema],

    invoice:{
        type: Schema.Types.ObjectId,
        ref: 'Invoice'
    }


});

我想要的是只返回 client.phoneclient.email 加上 orderdetails.status 但如果可能仍保留 reference 字段

我尝试过使用lean()populate(),但没有成功。我缺少什么非常简单的东西吗?或者我想要实现的不是那么容易? 谢谢!

【问题讨论】:

  • 您的 get 调用是什么样的?你可以使用 mongodb 投影
  • 需要查看您当前的查询

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

您可以像这样指定要返回的字段:

Order.findOne({'_id' : id})
        .select('client.phone client.email orderdetails.status reference')
        .exec(function(err, order) {
        //
});

替代语法

Order.findOne({'_id' : id})
    .select('client.phone client.email orderdetails.status reference')
    .exec(function(err, order) {
      //
});

我在这里做了一些假设,但你应该能够看到这个想法。

【讨论】:

  • 按我的意愿工作。谢谢!
  • 我从 node 开始,我正在使用带有 typescript 的 Nest,当我使用过滤器进行查询并返回一些特定字段(如 java)时,是否有必要(最佳实践)将结果映射到 dto?
【解决方案2】:

只需这样做:-

Order 是在 mongoose 中注册的型号名称。

Order.findById(id) // set id you have to get 
   . populate('client')
    .select('client.phone client.email orderdetails.status reference')
    .exec(function(err, order) {
      //
});

【讨论】:

    【解决方案3】:

    你可以使用投影。

    await Order.findById(diaryId, {phone: 1, email: 1, status: 1})
    

    如果 phone:1 设置为 1,则包含,如果 phone:0,则排除。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2021-07-22
      • 2019-05-04
      • 2016-09-01
      • 2012-10-27
      • 2021-03-22
      • 2016-02-17
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多