D
D
dpablo_escobarr2021-02-10 18:55:42
Mongoose
dpablo_escobarr, 2021-02-10 18:55:42

How to query mongoDB using mongoose?

It is necessary to add a field to the existing output - countViews: Number , which will contain the number of records from the child views array. I want to implement this without creating an additional field in the database for this purpose.

I want instead of this output from the database:

[{
    "created": 1611739142028,
    "author": "name",
    "tages": "asd asd",
    "url": "urlexample",
    "views": ["vasya", "petya"],
    "likes": 0,
    "comments": 0,
    "moderate": true,
    "timeToRead": 2.9,
    "__v": 0
},
{
    "created": 1611739142028,
    "author": "name",
    "tages": "asd asd",
    "url": "urlexample",
    "views": ["vasya", "petya"],
    "likes": 0,
    "comments": 0,
    "moderate": true,
    "timeToRead": 2.9,
    "__v": 0
}]

get this:

[{
    "created": 1611739142028,
    "author": "name",
    "tages": "asd asd",
    "url": "urlexample",
    "views": ["vasya", "petya"],
    "countViews": 2,
    "likes": 0,
    "comments": 0,
    "moderate": true,
    "timeToRead": 2.9,
    "__v": 0
},
{
    "created": 1611739142028,
    "author": "name",
    "tages": "asd asd",
    "url": "urlexample",
    "views": ["vasya", "petya"],
    "countViews": 2,
    "likes": 0,
    "comments": 0,
    "moderate": true,
    "timeToRead": 2.9,
    "__v": 0
}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Khokhlov, 2021-02-10
@dpablo_escobarr

https://docs.mongodb.com/manual/reference/operator...
Well, or just run through the array after receiving documents from the database

return docs.map((doc) => {
  doc.countViews =  doc.views.length;
  return doc;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question