Returning specific fields with mongoose(使用Mongoose返回特定字段)
本文介绍了使用Mongoose返回特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力完成一件非常容易的事情,但还是失败了。
我尝试做的是,当我在服务器上收到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) {
//
});
我在这里做了一些假设,但您应该能够看到想法。
这篇关于使用Mongoose返回特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:使用Mongoose返回特定字段
基础教程推荐
猜你喜欢
- 从快速中间件中排除路由 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
