I have a problem with push method with typescript with error ("Property 'push' does not exist on type 'ObjectId'.ts(2339)") and also have this error with user // Object is possibly 'null'.ts(2531) // and try this code in javascript and it's work fine but in Typescript not with 3 errors of user and push method.. and how we can add populate to add new post with user id attached to post schema.. and thank you in advance.
controller/feed.ts
export const createPost: RequestHandler = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error("Validation failed, entered data is incorrect.");
error.statusCode = 422;
throw error;
}
if (!req.file) {
const error = new Error("No image provided.");
error.statusCode = 422;
throw error;
}
const imageUrl = req.file.path;
const title = req.body.title;
const content = req.body.content;
let creator;
const post = new Post({
_id: new mongoose.Types.ObjectId(),
title: title,
content: content,
imageUrl: imageUrl,
creator: req.userId,
});
console.log(req.params.userId);
post
.save()
.then((result) => {
return User.findById(req.userId);
})
.then((user) => {
creator = user;
*user?*.posts.push(post); // error: Property 'push' does not exist on type 'ObjectId'.ts(2339)
// user without ? i have this error : Object is possibly 'null'.ts(2531)
return user?.save();
})
.then((result) => {
res.status(201).json({
message: "Post created successfully!",
post: post,
creator: { _id: creator._id, name: creator.name },
});
})
.catch((err) => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};
user.model.ts
import { model,Schema, Document,Types } from "mongoose";
export interface IUser extends Document {
email: string;
password: string;
name: string;
status: string;
posts: Types.ObjectId;
createdAt?: Date;
updatedAt?: Date;
}
const userSchema: Schema = new Schema(
{
_id: Schema.Types.ObjectId,
email: {
type: Schema.Types.String,
required: true,
},
password: {
type: Schema.Types.String,
required: true,
},
name: {
type: Schema.Types.String,
required: true,
},
status: {
type: Schema.Types.String,
default: "I am new!",
},
posts: {
type: Schema.Types.ObjectId,
ref: "Post",
},
},
{ timestamps: true, versionKey: false }
);
const User = model<IUser>("User", userSchema);
export default User;
export {};
post.model.ts
import { model,Schema, Document,Types } from "mongoose";
export interface IPost extends Document {
title: string;
imageUrl: string;
content: string;
creator: Types.ObjectId;
}
const postSchema = new Schema(
{
_id: Schema.Types.ObjectId,
title: {
type: Schema.Types.String,
required: true,
},
imageUrl: {
type: Schema.Types.String,
required: true,
},
content: {
type: Schema.Types.String,
required: true,
},
creator: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{ timestamps: true, versionKey: false }
);
const Post = model<IPost>("Post", postSchema);
export default Post;
export {};