简体   繁体   中英

Mongoose model.save() error - 'Cannot apply $inc to a value of non-numeric type'

I have 2 mongoose models in their own respective 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 );

Now, I am trying to create a new post, save it and have the object id be reflected in the user schema. For sake of simplicity, assume I have an async function where the model content is being passed as well as some sort of user id.

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 post belongs to

owner.postHistory.push(post);   <---Output now shows user with 1 post object within postHistory array

await owner.save();  <-- Error occurs here

This is where the error occurs. I get the following error:

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 followed the right process as per the mongoose docs: Mongoose Model Ref

I dont get this error message when I already have an array of post ids already embedded within User.postHistory in MongoDB. This only occurs when the User has an empty postHistory array (Think when the user has his first post associated with the user.

Any suggestions?

Figured out the solution. In MongoDB, for some reason, the _v property in a document was being saved as a string instead of int32.

For one of my documents, the _v prop was int32, but for another it was string. By changing _v to int32 on the new document, I am now able to create the references correctly.

Hopefully this helps someone. Always double check the type of your props within the document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM