【问题标题】:How to count documents with mongodb and node.js? [duplicate]如何使用 mongodb 和 node.js 计算文档? [复制]
【发布时间】:2017-09-14 09:07:18
【问题描述】:

我想将集合的文档数量保存在“const amount_documents”中。如这个问题中所述:如何获取猫鼬模型的所有计数?你不能简单地写

const amount_documents = User.count();

这样做的正确方法是什么?当我使用此代码时:

  var myCallback = User.count({}, function(err, count) {
    callback(count);
  });

它说“未定义回调”

【问题讨论】:

  • 你在哪里定义callback?我怀疑你的函数运行正常,但只是没有回调引用。试试看:var myCallback = User.count({}, function(err, count) { console.log(count); });

标签: node.js mongodb mongoose


【解决方案1】:

User.count 是异步的,使用这种语法,你必须在回调中执行你的代码,这样:

  User.count({}, function(err, count) {
    const amount_documents = count;
    // your code using the count
  });

如果你使用 promise 和 await/async 语法,你可以这样做:

const amount_documents = await User.count({});
// Your code using the count here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多