Nico
Nico

Reputation: 409

How to Return Mongoose Object Field (In Module.exports function)

So I have the following code:

var Mix = require('../models/mix');

module.exports = {
    mixTitle: function(mix_id) {
        return Mix.findOne({ 'mix_id' : mix_id }, 'title', function(err, mix){
          console.log(mix.title); // This correctly prints the title field
          return mix.title;
        });
    }
}

I import the Mix model and then can access the title field inside my callback, but is there any way to actually return the mix.title string value? Currently all I get is (what I think is) the query prototype ..

Query {
  _mongooseOptions: {},
  mongooseCollection: 
   NativeCollection {
     collection: { s: [Object] },
     opts: { bufferCommands: true, capped: false },
     name: 'mixes',
     collectionName: 'mixes',
     conn: 
      NativeConnection {
        base: [Object],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,

... etc

How would I properly write this exported function to just return the title field of my found Object?

Upvotes: 0

Views: 265

Answers (1)

alexmac
alexmac

Reputation: 19617

Mix.findOne is async function, you can get result of function immediately. You can pass callback parameter and get result there, or much better solution - use promises:

// mix-service.js
var Mix = require('../models/mix');

module.exports = {
    mixTitle: function(mix_id) {
        return Mix
          .findOne({ 'mix_id' : mix_id }, 'title')
          .then(mix => {
            console.log(mix.title); // This correctly prints the title field
            return mix.title;
          });
    }
};

// calling module
var mixSrvc = require('../mix-service');

mixSrvc
  .mixTitle(1)
  .then(mixTitle => console.log(mixTitle))
  .catch(err => console.log(err));

Upvotes: 1

Related Questions