Wednesday, 24 May 2017

Returning specific fields with mongoose

I'm trying to accomplish something really easy but still manage to fail.

What I am trying to do is when I get a get request on my server I want to return all documents BUT just the specific fields populated.

My schema goes as follows

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'
    }


});

What I want is to return only client.phone and client.email plus orderdetails.status but still retain reference field if possible

I have tried using lean() and populate() but had no luck with them. Is there anything utterly simple I am missing? Or what I am trying to achieve is not that easy? Thanks!



via Jack Wolther

No comments:

Post a Comment