Hey I have created a model User like so:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
status: {
type: String,
default: 'I am new!',
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post',
},
],
},
{ timestamps: true }
);
export const User = mongoose.model('User', userSchema);
I want to use the pull method to fetch a specific postId and clear it.
export const deletePost = async (req: Request, res: Response, next: NextFunction) => {
try {
const postId = req.params.postId;
const fetchedPost = await Post.findById(postId);
if (!fetchedPost) {
const error = new HttpError("Could not find post.", 404);
return next(error);
}
if (fetchedPost.creator.toString() !== req.userId) {
const error = new HttpError("Not Authorized!", 403);
return next(error);
}
clearImage(fetchedPost.imageUrl);
await Post.findByIdAndDelete(postId);
// Clearing User and Post relation
const user = await User.findById(req.userId)!;
if (user) {
user.posts.pull(postId);
await user.save();
}
res.status(200).json({ message: "Deleted post!" });
} catch (err) {
return next(new HttpError("Failed to delete a post", 500));
}
};
However I am getting error from my ts lsp
Property 'pull' does not exist on type 'ObjectId[]'.ts(2339) any
Have things changed in the the mongoose where pull method is deprecated and do I need to create pull util method manually or am I doing something wrong?
I think you should use Types.ObjectId
instead of Schema.Types.ObjectId
Here is the github thread where this was dicussed.
An excerpt:
mongoose.Types are the object you work with within a mongoose document. These are special array subclasses, buffer subclasses, etc that we've hooked into or created special to ease updates and track changes.