'I want to gather all of the nested schema data in the same schema but i don't want it to be nested or put it in a new schema
I have a user schema and a nested likes schema
const {Schema,model} = require('mongoose')
const LikesSchema = new Schema({
Likes:Number,
})
const UsersSchema = new Schema({
Name:{type:String, required:true},
Email:{type:String ,required:true, unique:true},
PhoneNumber:{type:Number, required:true,unique:true},
Password:{type:String, required:true ,unique:true},
Likees:LikesSchema
})
const Likes = model('Like',LikesSchema)
module.exports = Likes
const Users = model('users', UsersSchema)
module.exports = Users
the schema code so in my server whenever a new user register I make a user with 0 likes
app.post('/Register',UserValidator,UserValidationResult,(req,res) =>{
Users.find({ Email:req.body.Email,Password:req.body.Password,Name:req.body.Name,PhoneNumber:req.body.PhoneNumber})
.exec()
.then(users => {
if(users.length >= 1 ){
return res.status(409).json({message:'This user information has been used'})
}
else{
bcrypt.hash(req.body.Password,10, function (err,hash){
if(err){
return res.status(500).json({
error: err,
message:'Server error'
})
}else{
const user = new Users ({
Email:req.body.Email,
Password:hash,
Name:req.body.Name,
PhoneNumber:req.body.PhoneNumber,
Likees:{Likes:0}
})
user.parent().save()
.then(result => res.status(201).json({message:'Registered successfully'}))
.catch(err => res.status(409).json({message:'Registeration failed'}))
}
})
}
})
})
what I did is I will run another function in my front end that sends a request to update the user likes from 0 to 1 when a user press the like button
app.post('/Likes',(req,res) =>{
Users.findOneAndUpdate({Email:req.body.Email , Name:req.body.Name},{
Likees:{Likes:1}}, (err,New) =>{
if (err){
console.log(err)
}else{
console.log(New)
res.json(New)
} })
})
what I want to do is I want to display all of the likes by all of the users in a state in my react app is there a way that I can gather all of the likes Numbers and send them to the front end to store them in a state in my react app
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
