Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
bobmoff Avatar asked Mar 14 '14 21:03

bobmoff


People also ask

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What is user _DOC in mongoose?

_doc exist on the mongoose object. Because mongooseModel. findOne returns the model itself, the model has structure (protected fields). When you try to print the object with console. log it gives you only the data from the database, because console.

What does the schema do in mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Does Mongoose require schema?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.


1 Answers

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.

like image 62
bobmoff Avatar answered Sep 28 '22 02:09

bobmoff