简体   繁体   English

NodeJS,猫鼬,返回变量

[英]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. 目的是将函数的结果分配给一个变量,我以后可以在POST上使用该变量将信息发送到我的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. 我想要的是捕获此数字“ num”:9到一个变量。 I created a function that query the mongodb through the model. 我创建了一个通过模型查询mongodb的函数。

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. 然后只是为了测试我将该函数分配给变量,然后尝试console.log它只是为了测试结果是否良好。

// =====================================
// 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. 您无法返回诸如findOne之类的异步函数的结果,需要使用回调。

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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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