1

I am trying to add an item to a MongoDB array with RESTAPI through Axios. I thought it would look similar to the push method but I have no idea how to do that.

my Model is of a person:

const Schema = mongoose.Schema;
const PersonSchema = new Schema({
    name: String,
    password: String,
    friends: [],
    missions: []
})

const personModel = mongoose.model('Person', PersonSchema);

I want to add a mission to the mission array of a person.

and for example, in order to add a new Person, I use NodeJS and API: (api.js)

router.post('/api/people', (req, res) => {
    const personToAdd = req.body;
    const newPersonPost = new personModel(personToAdd);
    newPersonPost.save((e) => {
        if (e) {
            console.log("error");
        }
    });
    res.json({
        msg: 'Received'
    })
});

and in the client side I use Axios:

axios({
                url: 'http://localhost:8080/api/people',
                method: 'POST',
                data: dataToUpdate
            })
                .then(() => {
                    console.log('axios sent info to server');
                }).catch((e) => {
                    console.log('error' + e);
                }) 

Thank you so much!

4 Answers 4

1

express

router.post('updating mission endpoint url', async (req, res) =>
try {
const query = { /* content */}; /* write a query to retrieve the concerned user by using a unique identifier */
let person = await personModel.findOne(query); 
person.missions.push(req.body.mission); 

personModel.save(); 
} catch (err) { 
console.log(err); 
} 
});

client

In the client side you just have to put the mission you want to add in data like you did above with the right endpoint url and you should add a unique identifier for the user you want to add mission to.

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

Comments

0

[] will not assign array type to your variable.

Change your schema file with the following:

const Schema = mongoose.Schema;
const PersonSchema = new Schema({
    name: { type: String },
    password: { type: String },
    friends: { type: Array },
    missions: { type: Array }
})

Comments

0

Update the db model entity file with following

First method:

const Schema = mongoose.Schema;
const PersonSchema = new Schema({
    name: String,
    password: String,
    friends: {type : Array},
    missions: {type : Array}
})

const personModel = mongoose.model('Person', PersonSchema);

Second Method :

const Schema = mongoose.Schema;
        const PersonSchema = new Schema({
            name: String,
            password: String,
            friends: [{ type: String }],
            missions: [{ type: String }]
        })
        
        const personModel = mongoose.model('Person', PersonSchema);

You can update the array object as per your requirements.

Comments

0

You just want to be using the $push update operator, very simple, like so:

db.collection.updateOne(
{
  _id: user._id
},
{
  "$push": {
    "missions": {
      mission: newMission
    }
  }
})

Mongo Playground

2 Comments

Hi! Thank you for your comment. can you please elaborate a little? where should I write this code? on the client side? and how do I connect to the DB without API?
No no, on the server side. you can't connect to the DB without an API, Atlas is offering a serverless offering which is the only service I know which exposes such API's with no server.

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.