Programing

몽구스 모델의 모든 수를 얻는 방법?

crosscheck 2020. 9. 13. 10:03
반응형

몽구스 모델의 모든 수를 얻는 방법?


데이터가 저장된 모델 수를 어떻게 알 수 있습니까? 의 방법이 Model.count()있지만 작동하지 않는 것 같습니다.

var db = mongoose.connect('mongodb://localhost/myApp');
var userSchema = new Schema({name:String,password:String});
userModel =db.model('UserList',userSchema);        
var userCount = userModel.count('name');

userCount어떤 메소드가 호출되어 진짜를 얻을 수 count있습니까?

감사


아래 코드가 작동합니다. countDocuments 사용에 유의하십시오 .

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

코드가 작동하지 않는 이유는 count 함수가 비동기식이고 값을 동 기적으로 반환하지 않기 때문입니다.

다음은 사용 예입니다.

userModel.count({}, function( err, count){
    console.log( "Number of users:", count );
})

collection.count는 더 이상 사용되지 않으며 향후 버전에서 제거됩니다. 컬렉션을 사용하십시오. countDocuments 또는 컬렉션. estimatedDocumentCount 대신.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

개체를 인수로 제공해야합니다.

userModel.count({name: "sam"});

또는

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

또는

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

최신 버전의 mongoose에서는 count ()가 더 이상 사용되지 않으므로 다음을 사용하십시오.

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

mongoose 문서와 Benjamin의 답변에 명시된 것처럼 Model.count () 메서드 는 더 이상 사용되지 않습니다. count ()를 사용하는 대신 대안은 다음과 같습니다.

Model.countDocuments (filterObject, callback)

컬렉션의 필터와 일치하는 문서 수를 계산합니다. 빈 개체 {}를 필터로 전달하면 전체 컬렉션 검색이 실행됩니다. 컬렉션이 큰 경우 다음 방법을 사용할 수 있습니다.

Model.estimatedDocumentCount ()

이 모델 방법은 MongoDB 컬렉션의 문서 수를 추정합니다. 이 메서드는 전체 컬렉션을 거치지 않고 컬렉션 메타 데이터를 사용하기 때문에 이전 countDocuments ()보다 빠릅니다. 그러나 메서드 이름에서 알 수 있듯이 db 구성에 따라 메타 데이터가 메서드 실행 시점에 컬렉션의 실제 문서 수를 반영하지 않을 수 있으므로 결과는 추정치입니다.

두 메소드 모두 몽구스 쿼리 객체를 반환하며 다음 두 가지 방법 중 하나로 실행할 수 있습니다. 나중에 쿼리를 실행하려면 .exec ()를 사용하십시오.

1) 콜백 함수 전달

예를 들어 .countDocuments ()를 사용하여 컬렉션의 모든 문서를 계산합니다.

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

또는 .countDocuments ()를 사용하여 특정 이름을 가진 컬렉션의 모든 문서를 계산합니다.

SomeModel.countDocuments({ name: 'Snow' }, function(err, count) {
    //see other example
}

2) .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():

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

Hope this helps!


As said before, you code will not work the way it is. A solution to that would be using a callback function, but if you think it would carry you to a 'Callback hell', you can search for "Promisses".

A possible solution using a callback function:

//DECLARE  numberofDocs OUT OF FUNCTIONS
     var  numberofDocs;
     userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

if you want to search the number of documents based on a query, you can do this:

 userModel.count({yourQueryGoesHere}, setNumberofDocuments);

setNumberofDocuments is a separeted function :

var setNumberofDocuments = function(err, count){ 
        if(err) return handleError(err);

        numberofDocs = count;

      };

Now you can get the number of Documents anywhere with a getFunction:

     function getNumberofDocs(){
           return numberofDocs;
        }
 var number = getNumberofDocs();

In addition , you use this asynchronous function inside a synchronous one by using a callback, example:

function calculateNumberOfDoc(someParameter, setNumberofDocuments){

       userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

       setNumberofDocuments(true);


} 

Hope it can help others. :)

참고URL : https://stackoverflow.com/questions/10811887/how-to-get-all-count-of-mongoose-model

반응형