0
I need to return a model function in my controller as if it were a "virtual" from Mongoose, actually in the controller I would specify via "populate" the function name and return the function in the return JSON of my controller function.
I do it in Laravel and I wonder if in Mongoose I can do it the same...
Follows codes for example:
Model:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Teste = mongoose.model('Teste');
const schema = new Schema({
testeField: {
type: String,
required: true
}
}, { toJSON: { virtuals: true }});
schema.virtual('testeInclude', {
ref: 'Teste',
localField: 'testeField',
foreignField: '_id',
justOne: false, // set true for one-to-one relationship
options: { sort: { t: -1 } }
});
module.exports = mongoose.model('Teste', schema);
This would be a virtual 1-to-1 or 1 for many...
This is the model I would need:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Teste = mongoose.model('Teste');
const schema = new Schema({
testeField: {
type: String,
required: true
}
}, { toJSON: { virtuals: true }});
schema.virtual('testeInclude', function () {
return 123;
});
module.exports = mongoose.model('Teste', schema);
Below return in controller with populate:
var teste = function(req, res, next){
Teste.find({}).populate("testeInclude").then(x => {
res.status(200).send({ x });
}
}).catch(e => {
res.status(200).send({ "error" });
});
}
I accept other ways to do this, it doesn’t have to be with virtual and populate.. Suggestions ?