How to add temporary properties of mongoose object only for response that is not stored in database

I would like to fill out a couple of additional temporary properties with additional data and send back 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 properties will not be added to the tournament object, and therefore not in response.

+8
javascript mongoose
source share
1 answer

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

I cannot add the properties of the Mongoose object, I have to convert it to a regular JSON object using the .toJSON() or .toObject() methods.

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

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

... which also creates its own js objects.

+15
source share

All Articles