简体   繁体   中英

NodeJS, Mongoose, return variable

thanks in advance for your time and answers:

I've been trying to do something that "should" be easy but it's being me crazy.

the objective is to asign the result of a function to a variable that i can use later on a POST to send information to my MongoDB.

I've a model with a document as:

{ "__v" : 0, "_id" : ObjectId("54ad1aa637ce5c566c13d18f"), "num" : 9 }

What i want is to capture this number "num" : 9 to a variable. I created a function that query the mongodb through the model.

function getNum(){
      var Num = require('./models/num.js');

      var callback = function(){
             return function(err, data) {
                if(err) {
                  console.log("error found: " + err);
                }
                console.log("the number is: " + data.num);
               }
            };
      return Num.findOne({}, callback());
};

then just to test i assign that function to a variable and try to console.log it just to test if the result is fine.

// =====================================
// TESTING ==============================
// =====================================

app.get('/testing',function(req, res, next){
var a = getNum();
console.log(a);
});

My output is:

{ _mongooseOptions: {},
  mongooseCollection: 
   { collection: 
  { db: [Object],
    collectionName: 'num',
    internalHint: null,
    opts: {},
    slaveOk: false,
    serializeFunctions: false,
    raw: false,
    pkFactory: [Object],
    serverCapabilities: undefined },
 opts: { bufferCommands: true, capped: false },
 name: 'num',
 conn: 
  { base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: undefined,
    pass: undefined,
    name: 'project',
    options: [Object],
    otherDbs: [],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: true,
    _events: {},
    db: [Object] },
 queue: [],
 buffer: false },
 model: 
  { [Function: model]
   base: 
    { connections: [Object],
    plugins: [],
    models: [Object],
    modelSchemas: [Object],
    options: [Object] },
 modelName: 'Num',
 model: [Function: model],
 db: 
  { base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: undefined,
    pass: undefined,
    name: 'project',
    options: [Object],
    otherDbs: [],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: true,
    _events: {},
    db: [Object] },
 discriminators: undefined,
 schema: 
  { paths: [Object],
    subpaths: {},
    virtuals: [Object],
    nested: {},
    inherits: {},
    callQueue: [Object],
    _indexes: [],
    methods: {},
    statics: {},
    tree: [Object],
    _requiredpaths: undefined,
    discriminatorMapping: undefined,
    _indexedpaths: undefined,
    options: [Object],
    _events: {} },
 options: undefined,
 collection: 
  { collection: [Object],
    opts: [Object],
    name: 'num',
    conn: [Object],
    queue: [],
    buffer: false } },
  op: 'findOne',
  options: {},
 _conditions: {},
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: 
 { collection: 
  { collection: [Object],
    opts: [Object],
    name: 'num',
    conn: [Object],
    queue: [],
    buffer: false } },
  _castError: null }
**the number is: 9**

This is one of the results i can get in other aproaches i get undefined.

Can anyone wonder what can i do to solve this?

Again thanks for your help.

You can't return the result of an asynchronous function like findOne , you need to use callbacks.

So it would need to be rewritten as something like:

function getNum(callback){
  var Num = require('./models/num.js');

  return Num.findOne({}, callback);
};

app.get('/testing',function(req, res, next){
  getNum(function(err, a) {
    console.log(a);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM