Return model function in controller

Asked

Viewed 43 times

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 ?

1 answer

0


I got something similar to what I need but without using populate, follow example: Using the library Mongoose-Fill

Model:

var mongoose = require('mongoose-fill');
schema.fill('teste', function(callback){
    this.db.model('Model')
        .findById("5ddd80bafff20707a5434adb")
        .exec(callback)
});

Controller:

Model.find({}).fill('teste').then(x => {
    console.log(x);
}).catch(e => {
    console.log(e);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.