bobmoff
bobmoff

Reputation: 2485

How do I add temporary properties on a mongoose object just for response, which is not stored in database

I would like to fill a couple of extra temporary properties with additional data and send back to the response

'use strict';

var mongoose = require('mongoose');
var express = require('express');
var app = express();

var TournamentSchema = new mongoose.Schema({
    createdAt: { type: Date, default: Date.now },
    deadlineAt: { type: Date }
});

var Tournament = mongoose.model('Tournament', TournamentSchema);

app.get('/', function(req, res) {
    var tournament = new Tournament();

    // Adding properties like this 'on-the-fly' doesnt seem to work
    // How can I do this ?
    tournament['friends'] = ['Friend1, Friend2'];
    tournament.state = 'NOOB';
    tournament.score = 5;
    console.log(tournament);
    res.send(tournament);
});

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

But the properties wont get added on the Tournament object and therefor not in the response.

Upvotes: 36

Views: 17645

Answers (1)

bobmoff
bobmoff

Reputation: 2485

Found the answer here: Unable to add properties to js object

I cant add properties on a Mongoose object, I have to convert it to plain JSON-object using the .toJSON() or .toObject() methods.

EDIT: And like @Zlatko mentions, you can also finalize your queries using the .lean() method.

mongooseModel.find().lean().exec()

... which also produces native js objects.

Upvotes: 61

Related Questions