Currently, I have set up 2 mongoose models in separate files.
const userSchema = new mongoose.Schema({
name:{type: String, required: true},
postHistory:[{type: mongoose.Schema.Types.ObjectId, ref: "Posts"}]
)};
module.exports = mongoose.model("User", userSchema );
const postSchema = new mongoose.Schema({
name:{type: String, required: true},
post:[{postName:String, postContent:String}]
)};
module.exports = mongoose.model("Posts", postSchema );
My goal now is to create a new post, save it, and ensure that the object id reflects in the user schema. Let's assume there is an async function where the model content is passed along with a user id for simplicity.
const post = new Posts({name:'John', post:[{postName:'My Comment', postContent:'My Full comment'}]);
await post.save(); <---This works as intended
const owner = await User.findById(userId); <-- This retrieves the specific user the post belongs to
owner.postHistory.push(post); <---Output now shows user with 1 post object within postHistory array
await owner.save(); <-- Error occurs here
The error arises at this point, throwing the following message:
message": "Cannot apply $inc to a value of non-numeric type. {_id: ObjectId('5e7908fd1e2e656d81a9ba05')} has the field '__v' of non-numeric type string"
I believe I have followed the correct process based on the mongoose documentation: Mongoose Model Ref
This error does not occur when there is already an array of post ids embedded within User.postHistory in MongoDB. It only happens when the User has an empty postHistory array (such as when the user associates their first post).
Any suggestions or insights on overcoming this issue?