getting schema attributes from Mongoose Model

后端 未结 9 1830
时光说笑
时光说笑 2020-12-01 06:19

I\'m using Mongoose.js to create models with schemas.

I have a list of models (many) and at times I\'d like to get the attributes/keys that make up a particular mo

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 06:41

    Solution for lodash, function which picked all schema properties, excluding specified

    _.mixin({ pickSchema: function (model, excluded) {
        var fields = [];
        model.schema.eachPath(function (path) {
           _.isArray(excluded) ? excluded.indexOf(path) < 0 ? fields.push(path) : false : path === excluded ? false : fields.push(path);
        });
        return fields;
       }
    });
    
    _.pickSchema(User, '_id'); // will return all fields except _id
    
    _.pick(req.body, _.pickSchema(User, ['_id', 'createdAt', 'hidden'])) // all except specified properties
    

    read more here https://gist.github.com/styopdev/95f3fed98ce3ebaedf5c

提交回复
热议问题