Hello everyone, like I had understood, the mongoose find() method gives me all documents from a collection. Now I have the issue in my frontend, that I am able to map through my users collection, but when I update userData, I get the error:
user.map is not a function
I debugged this error and found out, that find() gives not back an array, like I have expected, but it is an object, so that I cannot use the map() method. What I do wrong? Thanks for your help.
That is my model:
import mongoose, { Types } from 'mongoose';
export interface UserDocument extends mongoose.Document{
vorname:string;
nachname:string;
username:string;
email:string;
street:string;
number:string;
plz:string;
city:string;
password:string;
isAdmin:boolean;
createdAt: Date;
updatedAt: Date;
_doc?: any;
organization: Types.ObjectId;
}
const UserSchema = new mongoose.Schema<UserDocument>({
vorname:{type:String, required:true},
nachname:{type:String, required:true},
username:{type:String, required:true },
email:{type:String, required:true },
street:{type:String, required:true },
number:{type:String, required:true },
plz:{type:String, required:true },
city:{type:String, required:true },
password:{type:String, required:true },
isAdmin:{type:Boolean, default:false},
organization: { type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }
},
{timestamps:true}
)
const User = mongoose.model<UserDocument>('User', UserSchema);
export default User;
My Routes:
userRouter.put('/:id', verifyTokenAndAuthorization, async (req:Request, res:Response)=>{
try{
const updatedUser = await User.findByIdAndUpdate(req.params.id,{
$set: req.body,
},{new:true})
res.status(200).json(updatedUser);
} catch(error){
res.status(404)
throw new Error("User not found");
}
});
userRouter.get('/find', verifyTokenAndAdmin, async (req:Request, res:Response)=>{
try{
const allUsers = await User.find();
res.status(200).json(allUsers)
console.log(typeof allUsers); //gives back object
} catch(error){
res.status(404).json("Users not found");
}
});