Mongoose Saved _id'ss as a string instead of ObjectId

前端 未结 1 1275
谎友^
谎友^ 2021-01-21 08:30

Using Nodejs with Mongodb and Mongoose.

I just found out that Mongoose/Mongodb has been saving the auto generated _id field as a string as opposed to an ObjectId. Mongod

相关标签:
1条回答
  • 2021-01-21 08:59

    This is a pretty specific question, but if anyone happens to stumble upon a similar issue, my problem was that I wrote a file with all my documents as a json to use mongoimport on a remote server.

    The issue was that JSON.stringify() will convert an objectId to a string. To fix it I wrote just wrote a small script to loop through all the objects in my users array and convert all _id's back to objectId's with the following command:

    var mongoose = require('mongoose');
    user._id = mongoose.Types.ObjectId(users[i]._id);
    

    Then calling Model.create() on my mongoose model with the updated documents to bulk insert, and deleted the original documents

    0 讨论(0)
提交回复
热议问题