35

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.

bobmoff
  • 2,415
  • 3
  • 25
  • 32
  • Your code works for me... are you sure? Can you add some console.log just before sending response? – farvilain Mar 14 '14 at 23:38
  • I updated the code to be runnable and with console.log. The log is also without the added properties. How do I add more properties to the response without risking them being added to the databas ? – bobmoff Mar 15 '14 at 11:22
  • @farvilain updated question, I dont think it was clear enough – bobmoff Mar 15 '14 at 11:36

1 Answers1

59

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.

bobmoff
  • 2,415
  • 3
  • 25
  • 32