Hsn
Hsn

Reputation: 1238

Pushing data into Mongoose Model array?

Hi i am trying to push string into an array in mongoose. But it is not updating.

My Model is

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  project:{
    type: new mongoose.Schema({
      name: {
        type: [String], //tryxing to push data here
        required: true,
        minlength: 2,
        maxlength: 50
      }
    }),

  },
  isAdmin: Boolean
});

and in the code i am doing

router.put('/addProject', auth, async (req, res) => { //To update password
user = await User.findByIdAndUpdate(req.user._id,{project:{$push :{name:req.body.projectname}},new :true});

        /*********OR********/
        User.findOneAndUpdate(
           { _id: req.user._id }, 
           {project:{ $push: { name: req.body.projectname  } }},
          function (error, success) {
                if (error) {
                    console.log(error);
                } else {
                    console.log(success);
                }
            });

i tried both the approaches but it is showing me empty array. And if there is already data in it get deleted everytime i run this route.. Thanks

Upvotes: 0

Views: 76

Answers (1)

Fraction
Fraction

Reputation: 12954

You need to change the project and name fields to:

project:{
    name: [{
        type: String, // and not `type: [String]`
        required: true,
        minlength: 2,
        maxlength: 50
      }
    }]
},

The final schema would be:

// user.model.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  project:{
    name: [{
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
      }]
  },
  isAdmin: Boolean
});

export default User = mongoose.model('User', userSchema);

Then in your controller:

import User from './user.model';

router.put('/addProject', auth, async (req, res) => {
user = await User.findByIdAndUpdate(req.user._id, 
  { $push: { 'project.name': req.body.projectname }, { new: true });
...

Edit: To remove an element from the array use $pull:

await User.findByIdAndUpdate(req.user._id, 
  { $pull: { 'project.name': req.body.projectname }, { new: true });
...

Upvotes: 1

Related Questions