乐闻世界logo
搜索文章和话题

How to get all count of mongoose model

5 个月前提问
3 个月前修改
浏览次数75

6个答案

1
2
3
4
5
6

在Mongoose中,如果您想获取所有model的总数,您通常需要对每个model分别执行一个count操作,并将结果累加。下面给出一个如何在Mongoose中实现这一过程的示例:

假设您有多个model,比如User, Post, 和 Comment,您可以如下进行:

javascript
const mongoose = require('mongoose'); // 假设您已经定义并连接了models const User = mongoose.model('User'); const Post = mongoose.model('Post'); const Comment = mongoose.model('Comment'); async function getTotalCountOfModels() { try { // 分别获取每个model的数量 const userCount = await User.countDocuments().exec(); const postCount = await Post.countDocuments().exec(); const commentCount = await Comment.countDocuments().exec(); // 将所有model的数量累加 const totalCount = userCount + postCount + commentCount; console.log(`总数为: ${totalCount}`); return totalCount; } catch (error) { console.error('获取model总数时发生错误', error); throw error; } } // 调用函数 getTotalCountOfModels() .then(total => console.log('总数量为:', total)) .catch(err => console.error(err));

在这个例子中,countDocuments() 方法被用来计算每个model中document的数量。我们通过async/await进行异步操作,并使用try/catch来处理可能出现的错误。

这是一个基础的例子,实际应用中可能会涉及更复杂的逻辑,比如过滤条件、关联查询等。此外,如果模型非常多,可能需要一个更自动化的方法来循环处理所有模型,而不是手动一个一个地调用。

2024年6月29日 12:07 回复

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

Here's an example of usage:

shell
userModel.count({}, function( err, count){ console.log( "Number of users:", count ); })
2024年6月29日 12:07 回复

The code below works. Note the use of countDocuments.

shell
var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost/myApp'); var userSchema = new mongoose.Schema({name:String,password:String}); var userModel =db.model('userlists',userSchema); var anand = new userModel({ name: 'anand', password: 'abcd'}); anand.save(function (err, docs) { if (err) { console.log('Error'); } else { userModel.countDocuments({name: 'anand'}, function(err, c) { console.log('Count is ' + c); }); } });
2024年6月29日 12:07 回复

You should give an object as argument

shell
userModel.countDocuments({name: "sam"});

or

shell
userModel.countDocuments({name: "sam"}).exec(); //if you are using promise

or

shell
userModel.countDocuments({}); // if you want to get all counts irrespective of the fields

For the older versions of mongoose, use

shell
userModel.count({name: "sam"});
2024年6月29日 12:07 回复

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

shell
userModel.countDocuments(query).exec((err, count) => { if (err) { res.send(err); return; } res.json({ count: count }); });
2024年6月29日 12:07 回复

Background for the solution

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

Model.countDocuments(filterObject, callback)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

The solution

Option 1: Pass a callback function

For example, count all documents in a collection using .countDocuments():

shell
someModel.countDocuments({}, function(err, docCount) { if (err) { return handleError(err) } //handle possible errors console.log(docCount) //and do some other fancy stuff })

Or, count all documents in a collection having a certain name using .countDocuments():

shell
someModel.countDocuments({ name: 'Snow' }, function(err, docCount) { //see other example }

Option 2: Use .then()

A mongoose query has .then() so it’s “thenable”. This is for a convenience and query itself is not a promise.

For example, count all documents in a collection using .estimatedDocumentCount():

shell
someModel .estimatedDocumentCount() .then(docCount => { console.log(docCount) //and do one super neat trick }) .catch(err => { //handle possible errors })

Option 3: Use async/await

When using async/await approach, the recommended way is to use it with .exec() as it provides better stack traces.

shell
const docCount = await someModel.countDocuments({}).exec();

Learning by stackoverflowing,

2024年6月29日 12:07 回复

你的答案