NodeJS 中的mongoDB设置指定字段的隐藏,查询的时候强制显示指定隐藏的字段

NodeJS 中的mongoDB设置指定字段的隐藏,查询的时候强制显示指定隐藏的字段

这里使用的是基于RESTful API的规范创建的请求地址
  1. 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}
    			}
    		]
    	}
    })
    
  2. 使用查询指定的字段字段 请求地址localhost:3000/user/:id => localhost:3000/user/2 => id=2
    UserSchema.findById(id)
    
    可以看到没有显示password locations educations字段的内容
    在这里插入图片描述
  3. 指定查询隐藏的字段, 在查询的时候拼接.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版权协议,转载请附上原文出处链接和本声明。