I want to update array of objects – profiles by using input
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?
2
Answers
you can use the %push operator in moongose
the
findOneAndUpdate
function is used to find user. and update it .as you askedFirst, you specified in your schema that
profiles
field is of typearray of ObjectIds
. It looks like you want it to be of typeString
instead, since you are trying the push thename
inside.So, you should first change your Schema model:
Now, you can push new items to that array like this: