从查询猫鼬中删除字段

时间:2019-05-29 07:07:18

标签: node.js mongoose

我的用户模型具有名称,...,密码,resetToken,resetTokenExp属性。

如果我查询用户(findById,find({}),...),我想删除密码,resetToken和resetTokenExp字段

User.findById(id)
  .select('-password -resetToken -resetTokenExp')  
  .exec()

我可以使用select,但是这些字段是常见的字段,我不想每次查询时都键入select。如何设置为用户架构全局删除这些字段

2 个答案:

答案 0 :(得分:0)

您可以使可重复使用的功能类似

因此,默认情况下,这三个字段将从结果中排除

const data$ = this.store.select(selectors.yourCombinedSelector)

答案 1 :(得分:0)

在您的用户模型架构中,请参考以下代码。

您可以使用猫鼬转换行为Link

下面的代码将帮助您全局删除密码,resetToken和resetTokenExp。

在此代码中,您还可以将 _id 替换为 id

UserModel.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    password: String,
    resetToken: String,
    resetTokenExp: String

}, {
    timestamps: true,
    toObject: {
      transform: function (doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.password;
        delete ret.resetToken
        delete ret.resetTokenExp
        return ret;
     }
   }
  });

module.exports = mongoose.model('User', userSchema);