NodeJS, Mongoose, return variable

NodeJS, Mongoose, return variable

本文关键字:variable return Mongoose NodeJS      更新时间:2023-09-26

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

我一直在尝试做一些"应该"容易的事情,但这让我很疯狂。

目标是将函数的结果分配给一个变量,我稍后可以在 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());
};

然后只是为了测试,我将该函数分配给一个变量并尝试控制台.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**

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

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

再次感谢您的帮助。

不能像 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);
  });
});