NodeJS 中的mongoDB设置指定字段的隐藏,查询的时候强制显示指定隐藏的字段
这里使用的是基于RESTful API的规范创建的请求地址
- 在
Schema创建用户的时候可以使用select:false设置该字段在查询的时候不显示,这里设置了locations educations字段在查询的时候不显示const mongoose = require("mongoose") const { Schema, model } = mongoose const UserSchema = Schema({ name: {type: String,required: true}, password: {type: String,require: true,select: false}, locations: {type: [{type: String}],select: false}, educations: { type: [ { school: {type: String}, admission: {type: Number} } ] } }) - 使用查询指定的字段字段 请求地址
localhost:3000/user/:id=>localhost:3000/user/2=>id=2
可以看到没有显示UserSchema.findById(id)password locations educations字段的内容
- 指定查询隐藏的字段, 在查询的时候拼接
.select('+educatons +locations')请求地址localhost:3000/user/2?fields=locations;educations注意: 在
.select('+a +b')的时候字段+a和+b之间有一个空格async get_queryById(ctx) { const {fields} = ctx.query let getselect if(fields) { getselect = fields.split(";").filter(f => f).map(item => `+${item} `).join("") getselect = getselect.slice(0,getselect.length -1) } else { getselect = '' } const {id} = ctx.params ctx.body = await User.findById(id).select(getselect) }

版权声明:本文为weixin_43972992原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。