chemitaxis
chemitaxis

Reputation: 14889

Map moongose object to DTO object in expressjs

I would like to parse objects from moongose result to DTOs for my views. I have a query example here, that return a result mongoose object:

const returnedData = (err, result) => {  
        //Result object is a schema from Moongose 
        cb(err, result);
    };

Text.findOne({}).exec(returnedData); 

My Text schema example:

const mongoose = require('mongoose');

const textSchema = new mongoose.Schema({

    TextMessage: String,
    ZIndex: Number,
    Color: String,
    FontSize: String,
    FontFamily: String 

}, { timestamps: true , collection: 'Text'});


const Text = mongoose.model('Text', textSchema);

module.exports = Text;

My DTO object:

let dto = 
{
    TextMessage: null,
    _id: null

}

My idea is "auto map" the properties values from Text object to my dto object, and discard values like timestamps.

Any ideas or library that make this automatically? Thanks!

Upvotes: 1

Views: 4667

Answers (1)

satish chennupati
satish chennupati

Reputation: 2650

This might come handy for you

http://mongoosejs.com/docs/api.html#document_Document-toObject

Since mongoose returned objects are basically modeled after the Document the above tells how it will convert it to plain javascript object directly.

you can also validate sync's after conversions.

Upvotes: 3

Related Questions