Home > Software engineering >  How can i push into schema array of mongoose?Initial array is empy
How can i push into schema array of mongoose?Initial array is empy

Time:12-26

I want to update array of objects - profiles by using input enter image description here

I use express,mongoose in reactjs. I have schema --

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const validator = require("validator");
const { ObjectId } = mongoose.Schema.Types;

const userSchema = new mongoose.Schema({
  email:{
    type: String,
    required: true,
    minlength: 4,
    unique: true,
    validate: {
      validator(email) {
        return validator.isEmail(email);
      },
    },
},
  password:{
    type: String,
    required: true,
    minlength: 5,
    select: false,
  },
  profiles:[ // array of user's profile
    {
      type:ObjectId,
      name:String,
    }
  ]

})

this is my route ---

router.post('/createProfile', createProfile);

what i tryed ---

module.exports.createProfile = (req,res) =>{
  
  const {name} = req.body;
  console.log(name)
  User.push(profiles,name)
  .then((result)=>res.send(result))
  .catch((err)=>console.log(err))

}

I dont know what the coreect way to use push. Do i need to use push? Is my chema for profiles OK?

CodePudding user response:

First, you specified in your schema that profiles field is of type array of ObjectIds. It looks like you want it to be of type String instead, since you are trying the push the name inside.

So, you should first change your Schema model:

profiles:[ // array of user's profile
  {
    type: String,
  }
]

Now, you can push new items to that array like this:

User.updateOne(
  { _id: req.user._id },
  { $push: { profiles: name } }
)

CodePudding user response:

you can use the %push operator in moongose

module.exports.createProfile = (req, res) => {
  const { name } = req.body;

  User.findOneAndUpdate(
    { _id: req.user._id },  
    { $push: { profiles: { name } } },
    { new: true, useFindAndModify: false }  
  )
  .then((result) => res.send(result))
  .catch((err) => console.log(err))
};

the findOneAndUpdate function is used to find user. and update it .as you asked

  • Related