我正在努力完成一些非常简单的事情,但仍然失败了。
我想做的是,当我在服务器上收到 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.phone
和 client.email
加上 orderdetails.status
但仍然保留 reference
字段(如果可能)
我尝试过使用 lean()
和 populate()
但没有成功。我缺少什么非常简单的东西吗?或者我想要实现的目标并不那么容易?
谢谢!
最佳答案
您可以像这样指定要返回的字段:
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) {
//
});
我在这里做了一些假设,但你应该能看出这个想法。
关于javascript - 使用 mongoose 返回特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44161946/