Answer the question
In order to leave comments, you need to log in
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
}]
[{
"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
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 questionAsk a Question
731 491 924 answers to any question