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.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
_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.
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.
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With