I am new to mongodb. I have a users db and collections dB in mongodb so I am trying to return all the collections for a particular user. in my collections schema, I have linked the user by using Types.ObjectId as shown below.
const CollectionsSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
title: {
type: String,
trim: true
},
overview: { type: String },
year: { type: String },
poster: { type: String },
rating: { type: Number },
movieId: { type: Number },
date: { type: Date, default: Date.now }
});
const Collections = mongoose.model("collections", CollectionsSchema);
module.exports = Collections;
Now I am creating a protected route that returns collections for a particular user as shown below
router.get("/movies/:user", requireAuth, (req, res) => {
User.findOne({ id: req.user.id }).then(user => {
Collections.find({ user: req.params.user })
.then(collections => {
if (collections.user.toString() !== req.user.id) {
return res.status(401).json({ notauthorized: "User not authorized" });
}
res.json(collections);
})
.catch(err => res.status(400).json("Error: " + err));
});
});
I get "Error: TypeError: Cannot read property 'toString' of undefined" because I have more than one collection, but when I use the findOne() as shown below
router.get("/movies/:user", requireAuth, (req, res) => {
// const userId = req.user._id;
User.findOne({ id: req.user.id }).then(user => {
Collections.findOne({ user: req.params.user })
.then(collections => {
if (collections.user.toString() !== req.user.id) {
return res.status(401).json({ notauthorized: "User not authorized" });
}
res.json(collections);
})
.catch(err => res.status(400).json("Error: " + err));
});
});
I successfully get one item from my collection.
Please, how can I use find(), loop through the collection and return all the items in a collection for a particular logged in user?
Thanking you all in anticipation of your help and time taken to look into this.
Blockquote
Blockquote