NodeJS,Mongoose,返回变量

时间:2015-01-13 16:03:12

标签: javascript node.js mongodb mongoose

提前感谢您的时间和答案:

我一直在努力做一些“应该”容易的事,但这让我很疯狂。

目标是将函数的结果赋予变量,以后我可以在POST上使用该变量将信息发送到我的MongoDB。

我有一个带有文档的模型:

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

我想要的是将这个数字“num”:9捕获到一个变量。我创建了一个通过模型查询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());
};

然后只是测试我将该函数分配给变量并尝试console.log它只是为了测试结果是否正常。

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

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

我的输出是:

{ _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**

这是我可以在其他方法中得到的结果之一我未定义。

有谁想知道我能做些什么来解决这个问题?

再次感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您无法返回findOne之类的异步函数的结果,您需要使用回调。

因此需要将其重写为:

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