0

I Want to push an object to an object inside an array on my MongoDB database. I'm trying to use $push submits[postDate] but it is giving me a red line under the first "[" . Any idea how to fix this?

My code:

        app.post('/add-submit', (req,res) => {

        let postDate = new Date();
        let dd = String(postDate.getDate()).padStart(2, '0');
        let mm = String(postDate.getMonth() + 1).padStart(2, '0');
        let yyyy = postDate.getFullYear();

        postDate = mm + '/' + dd + '/' + yyyy;

        subject = req.body.subject

        let pushValue = {
            time: req.body.time,
            description: req.body.description,
            date: postDate 
        }
            
        console.log(pushValue)

        console.log(postDate)

        let myquery = { username: req.body.username};
        let newvalues = { 
            $push : {
                submits[postDate] : {
                    [subject] : pushValue 
                }
            }                               
        }
        db.collection("users").updateOne(myquery, newvalues, (err, response) => {
            if (err) throw err;
            console.log("1 document updated");
            res.redirect('/users/'+req.body.id)
        });   
    })

But i get this error:

    D:\Users\willi\Documents\Node\StudyWebApp\server.js:186
                submits[postDate] : {
                       ^

SyntaxError: Unexpected token '['
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

This is what I want it to look like on the database:

mongodb database

Thanks.

1 Answer 1

1

It's not very clear your object model but I think you need use $ keyword.

To get the position in 'submits' you try submit[postDate] but there is no the right way, instead you need something like that:

db.collection.update({
  "username": "test",
  "submits.date": "16/10/2020"
},
{
  $push: {
    "submits.$.subjects": {
      "subjectName": {
        "time": "1234",
        "description": "desc"
      }
    }
  }
})

I will try to explain hoy it works, it's pretty simple.

The first object is where you want to 'point'. Is like a 'find', the place where you want to do the second part (the push). So using $ operator, you will work in that exact part of the document.

So, the second object ($push object) is the operation. Using submits.$.subjects the operation will be done at this particular section of document.

I have no tested it in Node but your code has myquery and newvalues variables so it should be the same and works.

By the way, I have replied the query here

Sign up to request clarification or add additional context in comments.

9 Comments

I did what you said to do and got no errors but nothing showed up on the database. Should I already have the array and objects on the database for it to work or does it create them automatically?
It is necessary to exists, because the query update the element that match the first object (username and submits.date). So if no element is found, none will be updated.
how do i check if it doesn't exist and what do I do then?
Please tell me how I'm going to create it in the first place :) It doesn't magically get on the database I have no idea how to get it there in the first place. When I try it adds random objects in between the objects I want to add. How do I create a object on the database that i can then add to with the code you provided.
Please be patient. If you are using Node you have the option to use the methods insertOne() or insertMany(). You can check the mongodb documentation
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.