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
JavaScript
x
66
66
1
var clientSchema = new Schema({
2
name:{
3
type: String,
4
required: true
5
},
6
phone:{
7
type: String,
8
required: true
9
},
10
email:{
11
type: String,
12
required: true
13
},
14
address: {
15
type: String,
16
required: false
17
}
18
});
19
20
var orderDetailsSchema = new Schema({
21
//isn't added to frontend
22
confirmed:{
23
type: Boolean,
24
required: true,
25
default: false
26
},
27
service:{
28
type: String,
29
required: true
30
},
31
delivery:{
32
type: String,
33
required: false
34
},
35
payment:{
36
type: String,
37
required: false
38
},
39
status:{
40
type: String,
41
required: true,
42
default: "new order"
43
},
44
});
45
46
var orderSchema = new Schema({
47
48
reference:{
49
type: String,
50
required: true
51
},
52
53
orderdetails: orderDetailsSchema,
54
55
client: clientSchema,
56
57
wheelspec: [wheelSchema],
58
59
invoice:{
60
type: Schema.Types.ObjectId,
61
ref: 'Invoice'
62
}
63
64
65
});
66
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!
Advertisement
Answer
You can specify the fields to return like this:
JavaScript
1
6
1
Order.findOne({'_id' : id})
2
.select('client.phone client.email orderdetails.status reference')
3
.exec(function(err, order) {
4
//
5
});
6
Alternative syntax
JavaScript
1
6
1
Order.findOne({'_id' : id})
2
.select('client.phone client.email orderdetails.status reference')
3
.exec(function(err, order) {
4
//
5
});
6
I’ve made a number of assumptions here, but you should be able to see the idea.