MongoDB private fields

I have a product model, it has many fields. Some of them are intended for the front-end application, for example:

var GameSchema = new Schema({
    likes: {
        type: [{
            type: Schema.ObjectId,
            ref: 'User'
        }]
    },
    likes_count: {
       type: Number
    }
});

I don't need a field likes_countin Db, but the controller returns only those fields that have a model, so I add the field likes_countto the db model

exports.some_method = function(req, res){
    var game = req.game;
    game.likes_count = game.likes.length
    res.json(game);
}

Is there a way to add additional data to the db model when sending a request without using it in db?

Please note that the problem is not in the field itself likes_count, I have different models, but this point has additional data about the db model.

+4
source share
2 answers

, , mongo_db mongoose (@robertklep) virtual , ,

GameSchema.virtual('likes_count').get(function () {
  return this.likes.length;
});

: ,

var UserSchema = new Schema({
    username: {
        type: String
    }
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});
+4

" db db?"

, , , , . MongoDB #.

MongoDB ; JSON, CRUD, MongoDB, .

JSON CRUD . JSON , INSERT, Modify Update. - JSON, broker\wrapper .. MongoDB, , , CRUD MongoDB.

0

All Articles