getting schema attributes from Mongoose Model

后端 未结 9 1820
时光说笑
时光说笑 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:27

    You can use Schema.prototype.obj that returns the original object passed to the schema constructor. and you can use it in a utility function to build the object you're going to save.

    import Todo from './todoModel'
    import { validationResult } from 'express-validator'
    
    const buildObject = (body) => {
        const data = {};
        const keys = Object.keys(Todo.schema.obj);
        keys.map(key => { if (body.hasOwnProperty(key)) data[key] = body[key] })
        return data;
    }
    
    const create = async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) return res.json(errors);
            let toBeSaved = buildObject(req.body);
            const todo = new Todo(toBeSaved);
            const savedTodo = await todo.save();
            if (savedTodo) return res.json(savedTodo);
            return res.json({ 'sanitized': keys })
        } catch (error) {
            res.json({ error })
        }
    }
    

    another way is to to not call the buildObject function and add it in two lines but you will write every key you want to save

    let { title, description } = req.body;
    let toBeSaved = { title, description };
    

    Using ES6 shorthand property names

提交回复
热议问题