使用 mongoose 和 node.js 获取 mLab 数据库中的文档总数

Getting total count of documents in mLab database using mongoose and node.js

更新

经过一些测试后,这有效:

Url.count({}, (err, data) => {
    console.log(data); // prints correct number
  });

但事实并非如此:

let len;
Url.count({}, (err, data) => {
  len = data;
});
console.log(len); // prints undefined

有没有办法获取长度数据,然后在后续操作中使用?

更新结束

我是 Node 和 Mongoose 的初学者。如何获取数据库集合中的文档总数(称为 "Url")?

我试过的一些代码:

1.

let len = Url.count();

2.

let len = Url.count({});

3.

let len = Url.find().count();

4.

let len = Url.find().count({});

5.

let len = function(done) {
    Url.count({}, (err, data) => {
      if (err) { done(err) }
      else { done(null, data) }
    });
};

我想找回一个数字,但是当我 console.log(len) 时,我得到了一个巨大的对象,它持续了一行又一行:

这是因为发生的操作顺序。首先发生这种情况

let len;

然后

Url.count({}, (err, data) => {
// Nothing is happening in here yet, still waiting to finish counting
});

然后

console.log(len); // So len IS undefined here. 

最后,一旦它完成计数:

len = data;

幸运的是猫鼬可以在这里帮助你,因为他们支持 .then

const numberOfUrls = Url.count({});
numberOfUrls.then(number => {
    // Now you can do whatever you need to do with the number
    console.log('number', number)
});

重要的一点,

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .exec() function.

http://mongoosejs.com/docs/promises.html

希望对您有所帮助!

我也曾为此苦苦挣扎。 Javascript 异步设计在这里发挥作用。 Console.log() 甚至在查询完成之前执行回调。

所以,您可以这样做:

let len;
Url.count({}, (err, data) => {
  len = data;
  console.log(len);
});

或者,将整个事情包装在一个 async 函数中:

// Just in case :)
mongoose.Promise = global.Promise;

async function dbOperations() {
  let len;
  // Ideally, you must also include error catching.
  // I am not, for now.
  len = await Url.count({}).exec();
  console.log(len);
}
dbOperations();

如果可行,请告诉我。