2

I am very new to MONGO DB so please bear with me.I am having a problem my array of objects is not working properly .

Here is my schema

const playerSchema = new mongoose.Schema({
    name: String,
    stats :{
        wins:Number,
        losses:Number,
        xp:Number
    },
    achievement:[
        {
        name:String,  
        date: String
            
        } 
    ]        });

Here is my document

const fluffy = new playerModel({
    "name":"nic raboy",
    "stats":{
        "wins":5,
        "losses":10,
        "xp":300
    },
    "achievements":[
        {"name":"Massive XP","date" :"25-08-21"},
        {"name":"instant loss","date":"24-08-21"}       
    ]

});

however in mongodb atlas its only showing array...and i cant see the objects inside... SCREENSHOT

2
  • Does this answer your question? Insert array of objects into MongoDB Commented Aug 25, 2021 at 17:46
  • Welcome to StackOverflow. Make sure to search before posting. Chances are someone already ran into the same or a similar issue in the past :) Commented Aug 25, 2021 at 17:47

2 Answers 2

1

Your schema is correct, it seems your input is wrong,

In schema definition you named it achievement, whereas in input document it is achievements. Correct this everything will work as you expected.

Explanation

The schema is expecting achievement and you inserted achievements, that is why it is shown as an empty array in the database. To avoids this kind of typos in the future, use the required flag.

const playerSchema = new mongoose.Schema({
    name: String,
    stats: {
        wins: Number,
        losses: Number,
        xp: Number
    },
    achievements: [
        {
            name: {
                type: String,
                required : true,
            },
            date: {
                type: String,
                required : true, // required informs for missing fields
            }
        }
    ]
})

Refer this link for more on validation

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

Comments

0

You can use insertMany see the doc here.
Of course, a while loop should work find calling multiple times insertOne, though I advise you to use the insertMany() method.

If you're new to MongoDB, I strongly encourage you to have a look at MongoDB University's MongoDB basics course as well as the MongoDB for JavaScript Developers course.

Comments

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.