KDogg
KDogg

Reputation: 455

Mongoose Saved _id'ss as a string instead of ObjectId

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. Mongodb shell output and sample documents:

> db.users.count({_id: {$type: 7}})
2
> db.users.count({_id: {$type: 2}})
4266

> db.users.find({_id: {$type: 7}},{_id:1}).limit(1)
{ "_id" : ObjectId("55f7df6fdb8aa078465ec6ec") }
> db.users.find({_id: {$type: 2}},{_id:1}).limit(1)
{ "_id" : "558c3472c8ec50de6e560ecd" }

The 4266 _id's (strings) come from this code:

var newUser = new ApiUser();

newUser.name = name;
newUser.link = link;
newUser.signupTime = new Date().getTime();
newUser.initialBrowser = initialBrowser;

newUser.save(function(err) {
     if (err)
          res.json(err);
     else
          res.json('success');
});

and the 2 _id's (ObjectId's) come from this code:

var newUser            = new User();
newUser.facebook.id    = profile.id;
newUser.facebook.token = token;
newUser.name  = profile.name.givenName + ' ' + profile.name.familyName;
if (profile.emails) {
    newUser.facebook.email = (profile.emails[0].value || '').toLowerCase();    
}
newUser.facebook.gender = profile.gender;
newUser.facebook.profilePic = profile.photos[0].value;

newUser.save(function(err) {
    if (err)
        return done(err);

    return done(null, newUser);
});

User() and ApiUser() both reference the same model. The one that saves ObjectId's is in a Facebook authentication Strategy with Passport.js

UPDATE: here is my user schema:

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var Schema   = mongoose.Schema;

// define the schema for our user model
var userSchema = Schema({
    name: String,
    email: String,
    link: Number,
    location: String,
    residence: String,
    age: Number,
    gender: String,
    subject: String,
    signupTime: Number,
    finishTime: Number,
    shared: String,
    search: String,
    shareFriend: String,
    local            : {
        email        : String,
        password     : String
    },
    facebook         : {
        id           : String,
        token        : String,
        email        : String,
        name         : String,
        gender       : String,
        profilePic   : String
    },
    interestsSummary: [Number],
    interests: [{name: String, iType: String}],
    valuesSummary: [Number],
    values: [{name: String}],
    traitsSummary: [Number],
    traits: [{name: String}],
    bio: String,
    friendInterests: Number,
    friendValues: Number,
    friendPersonality: Number,
    surveyLength: String,
    missedInfo: String,
    anythingElse: String,
    finalBrowser: String,
    consented: Boolean

}, {collection: "users"});

// generating a hash
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);

The issue is that I can't seem to query mongodb based on the ones that are strings, which is giving me problems:

        ApiUser.findById(req.body.friend,{name:1},function(err,user) {
            console.log(user);
        })  

This returns null unless I search for one of the 2 users with a proper _id. Req.body.friend is the _id, which is a string. How can I either change all the document's _id's to ObjectId's, or query the existing documents with string _id's?

Upvotes: 5

Views: 5418

Answers (1)

KDogg
KDogg

Reputation: 455

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

Upvotes: 4

Related Questions