K
K
komigor2021-05-10 23:51:44
Node.js
komigor, 2021-05-10 23:51:44

How to return field content with mongoose?

I have a mongo schema that looks like this:

//Main object
{
// в нем поля
user: "пум-пум-пум"
password:"абра-казябра"
tasks: [
{
   name: ''пум-пум-пум",
   startTime: "тут дата",
},

{
   name: ''пум-пум-пум",
   startTime: "тут дата",
},

{
   name: ''пум-пум-пум",
   startTime: "тут дата", 
 },
]
}


This is how I address her, that is, if there is a task that needs to be performed now, then we get the user
User.findOne( {"tasks.startTime":  toTimeZone( Date.now(),'Europe/Berlin').toString()}, (err ,user) => {


})


But here's the question, how can I get that object in tasks if I don't know what it is exactly? After all, it can be both the first and the last, and I need to return the name of the task whose time is the same as Date.now ().

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Romanov, 2021-05-11
@komigor

Can be done through Aggregation

let pipeline = [
    {
        $project: {
            tasks: {
                $filter: {
                    input: "$tasks",
                    as: "task",
                    cond: {$eq:["$$task.startTime",  toTimeZone( Date.now(), 'Europe/Berlin').toString()]}
                }
            }
        }
   }
]
db.user.aggregate(pipeline);

Only those elements will remain in the tasks array whose startTime field matches toTimeZone( Date.now(), 'Europe/Berlin').toString()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question