Mongoose - get number of matching fieldsMongoose - finding subdocuments by criteriaHow do I get started with Node.jsHow do I get the path to the current script with Node.js?How to paginate with Mongoose in Node.js?How to get GET (query string) variables in Express.js on Node.js?How do I update/upsert a document in Mongoose?How do I get ASP.NET Web API to return JSON instead of XML using Chrome?What is the “__v” field in MongooseFind MongoDB records where array field is not emptyPUT/ update operation fails in $resource AngularJS client in rest based app (mongoose insert / update issue).Mongoose. Postprocessing of awaiting data

Backpacking with incontinence

Security measures that could plausibly last 150+ years?

Should I put my name first or last in the team members list?

Why are prop blades not shaped like household fan blades?

Just how much information should you share with a former client?

Word for giving preference to the oldest child

What is the most 'environmentally friendly' way to learn to fly?

Feedback diagram

Went to a big 4 but got fired for underperformance in a year recently - Now every one thinks I'm pro - How to balance expectations?

Why are sugars in whole fruits not digested the same way sugars in juice are?

Is this popular optical illusion made of a grey-scale image with coloured lines?

How do Canadians get a visa to go to Saudi Arabia?

Can I shorten this filter, that finds disk sizes over 100G?

What is my clock telling me to do?

Derivative is just speed of change?

How do discovery writers hibernate?

Were there any unmanned expeditions to the moon that returned to Earth prior to Apollo?

The grades of the students in a class

Guidelines for writing a chord progression

How to let cacti grow even if no player is near?

Why did the United States not resort to nuclear weapons in Vietnam?

Why do we need a voltage divider when we get the same voltage at the output as the input?

Why should I use a big powerstone instead of smaller ones?

Best Ergonomic Design for a handheld ranged weapon



Mongoose - get number of matching fields


Mongoose - finding subdocuments by criteriaHow do I get started with Node.jsHow do I get the path to the current script with Node.js?How to paginate with Mongoose in Node.js?How to get GET (query string) variables in Express.js on Node.js?How do I update/upsert a document in Mongoose?How do I get ASP.NET Web API to return JSON instead of XML using Chrome?What is the “__v” field in MongooseFind MongoDB records where array field is not emptyPUT/ update operation fails in $resource AngularJS client in rest based app (mongoose insert / update issue).Mongoose. Postprocessing of awaiting data






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm writing a REST API in Node.js using Mongoose to access the MongoDB backend database. I want to provide an API endpoint that returns a count of the number of array objects that match a particular variationStatus.



This is what I have so far but it gives me an empty response...



//Get 'Approved' count
app.get("/v1/approvedcount", async (request, response) =>
var status = 'Approved';
try
var result = await variationsModel.find( 'variations.variationStatus': status ).exec().count();
response.send(result);
catch (error)
response.status(500).send(error);

)


And this is my model...



const variationsModel = mongoose.model("variations", 
"variations": [

"variationID": String,
"custID": String,
"projID": String,
"variationTitle": String,
"variationDesc": String,
"variationStatus": String,
"variationChargeable": String,
"variationCost": String,
"requireMaterial": String,
"variationRequestor": String,
"variationCreationDate": String,
"variationImages": [

"imageId": String

],
"variationCategory": String

]
);


Anyone help me out?



Thanks!










share|improve this question
























  • Please check stackoverflow.com/questions/16845191/….

    – Steve Gao
    Mar 27 at 1:18

















0















I'm writing a REST API in Node.js using Mongoose to access the MongoDB backend database. I want to provide an API endpoint that returns a count of the number of array objects that match a particular variationStatus.



This is what I have so far but it gives me an empty response...



//Get 'Approved' count
app.get("/v1/approvedcount", async (request, response) =>
var status = 'Approved';
try
var result = await variationsModel.find( 'variations.variationStatus': status ).exec().count();
response.send(result);
catch (error)
response.status(500).send(error);

)


And this is my model...



const variationsModel = mongoose.model("variations", 
"variations": [

"variationID": String,
"custID": String,
"projID": String,
"variationTitle": String,
"variationDesc": String,
"variationStatus": String,
"variationChargeable": String,
"variationCost": String,
"requireMaterial": String,
"variationRequestor": String,
"variationCreationDate": String,
"variationImages": [

"imageId": String

],
"variationCategory": String

]
);


Anyone help me out?



Thanks!










share|improve this question
























  • Please check stackoverflow.com/questions/16845191/….

    – Steve Gao
    Mar 27 at 1:18













0












0








0








I'm writing a REST API in Node.js using Mongoose to access the MongoDB backend database. I want to provide an API endpoint that returns a count of the number of array objects that match a particular variationStatus.



This is what I have so far but it gives me an empty response...



//Get 'Approved' count
app.get("/v1/approvedcount", async (request, response) =>
var status = 'Approved';
try
var result = await variationsModel.find( 'variations.variationStatus': status ).exec().count();
response.send(result);
catch (error)
response.status(500).send(error);

)


And this is my model...



const variationsModel = mongoose.model("variations", 
"variations": [

"variationID": String,
"custID": String,
"projID": String,
"variationTitle": String,
"variationDesc": String,
"variationStatus": String,
"variationChargeable": String,
"variationCost": String,
"requireMaterial": String,
"variationRequestor": String,
"variationCreationDate": String,
"variationImages": [

"imageId": String

],
"variationCategory": String

]
);


Anyone help me out?



Thanks!










share|improve this question














I'm writing a REST API in Node.js using Mongoose to access the MongoDB backend database. I want to provide an API endpoint that returns a count of the number of array objects that match a particular variationStatus.



This is what I have so far but it gives me an empty response...



//Get 'Approved' count
app.get("/v1/approvedcount", async (request, response) =>
var status = 'Approved';
try
var result = await variationsModel.find( 'variations.variationStatus': status ).exec().count();
response.send(result);
catch (error)
response.status(500).send(error);

)


And this is my model...



const variationsModel = mongoose.model("variations", 
"variations": [

"variationID": String,
"custID": String,
"projID": String,
"variationTitle": String,
"variationDesc": String,
"variationStatus": String,
"variationChargeable": String,
"variationCost": String,
"requireMaterial": String,
"variationRequestor": String,
"variationCreationDate": String,
"variationImages": [

"imageId": String

],
"variationCategory": String

]
);


Anyone help me out?



Thanks!







node.js json mongodb api mongoose






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 22:51









OctoOcto

437 bronze badges




437 bronze badges















  • Please check stackoverflow.com/questions/16845191/….

    – Steve Gao
    Mar 27 at 1:18

















  • Please check stackoverflow.com/questions/16845191/….

    – Steve Gao
    Mar 27 at 1:18
















Please check stackoverflow.com/questions/16845191/….

– Steve Gao
Mar 27 at 1:18





Please check stackoverflow.com/questions/16845191/….

– Steve Gao
Mar 27 at 1:18












1 Answer
1






active

oldest

votes


















0














You can use MongoDB aggregation pipeline to achieve the same.



Try this:



variationsModel
.aggregate([
$match :
'variations.variationStatus' : status

,
$unwind : "variations"
,
$match :
'variations.variationStatus' : status

,
$group :
_id : "$_id",
variations :
$push : '$variations'


,
$project :
count : $size : $variations

]);


Explanation:



  1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status


  2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.


  3. $match : To select only those documents which has variations.variationStatus:status


  4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status


  5. $project : This step is specifically to count the size of variations array , using $size.


For detailed info, please read MongoDb $unwind , $project and $size documentation.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367314%2fmongoose-get-number-of-matching-fields%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You can use MongoDB aggregation pipeline to achieve the same.



    Try this:



    variationsModel
    .aggregate([
    $match :
    'variations.variationStatus' : status

    ,
    $unwind : "variations"
    ,
    $match :
    'variations.variationStatus' : status

    ,
    $group :
    _id : "$_id",
    variations :
    $push : '$variations'


    ,
    $project :
    count : $size : $variations

    ]);


    Explanation:



    1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status


    2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.


    3. $match : To select only those documents which has variations.variationStatus:status


    4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status


    5. $project : This step is specifically to count the size of variations array , using $size.


    For detailed info, please read MongoDb $unwind , $project and $size documentation.






    share|improve this answer





























      0














      You can use MongoDB aggregation pipeline to achieve the same.



      Try this:



      variationsModel
      .aggregate([
      $match :
      'variations.variationStatus' : status

      ,
      $unwind : "variations"
      ,
      $match :
      'variations.variationStatus' : status

      ,
      $group :
      _id : "$_id",
      variations :
      $push : '$variations'


      ,
      $project :
      count : $size : $variations

      ]);


      Explanation:



      1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status


      2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.


      3. $match : To select only those documents which has variations.variationStatus:status


      4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status


      5. $project : This step is specifically to count the size of variations array , using $size.


      For detailed info, please read MongoDb $unwind , $project and $size documentation.






      share|improve this answer



























        0












        0








        0







        You can use MongoDB aggregation pipeline to achieve the same.



        Try this:



        variationsModel
        .aggregate([
        $match :
        'variations.variationStatus' : status

        ,
        $unwind : "variations"
        ,
        $match :
        'variations.variationStatus' : status

        ,
        $group :
        _id : "$_id",
        variations :
        $push : '$variations'


        ,
        $project :
        count : $size : $variations

        ]);


        Explanation:



        1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status


        2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.


        3. $match : To select only those documents which has variations.variationStatus:status


        4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status


        5. $project : This step is specifically to count the size of variations array , using $size.


        For detailed info, please read MongoDb $unwind , $project and $size documentation.






        share|improve this answer













        You can use MongoDB aggregation pipeline to achieve the same.



        Try this:



        variationsModel
        .aggregate([
        $match :
        'variations.variationStatus' : status

        ,
        $unwind : "variations"
        ,
        $match :
        'variations.variationStatus' : status

        ,
        $group :
        _id : "$_id",
        variations :
        $push : '$variations'


        ,
        $project :
        count : $size : $variations

        ]);


        Explanation:



        1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status


        2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.


        3. $match : To select only those documents which has variations.variationStatus:status


        4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status


        5. $project : This step is specifically to count the size of variations array , using $size.


        For detailed info, please read MongoDb $unwind , $project and $size documentation.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 5:47









        Ravi Shankar BhartiRavi Shankar Bharti

        5,7502 gold badges16 silver badges43 bronze badges




        5,7502 gold badges16 silver badges43 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367314%2fmongoose-get-number-of-matching-fields%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript