Brett Wagner
Brett Wagner

Reputation: 1154

Node, Mongoose: on save() "VersionError: No matching document found."

I'm new to mongoose so this is probably something very simple .. however.

I have a very simple schema that contains a simple array of numbers:

userSchema = new mongoose.Schema({
name        : String,
tag_id      : String,
badges      : [Number]
});

var user = mongoose.model( 'User', userSchema );

Later I want to add a badge to the user. So..

user.findOne({tag_id:tagid}, function(err,doc) {
     if (!doc) callback(false, 'no doc');

     // check to see if badge is in array, if not add it
     if ( doc.badges.indexOf(badgeNum) == -1 ) {
         doc.badges.push(badgeNum);
         doc.save( function(err) {
             if (err) callback( false, err );
             else callback( true, '');
         });
     } else {
         callback( false, 'user already had badge' )
     }
 });

However whenever I run that code I get a 'VersionError: No matching document found.'

I did a little googling and found reference to versioning being added in 3.x mongoose and that it's generally all handled internally. It should be noted that I loaded this user data straight into mongo via json and the mongo commandline ( so it wouldn't have the versioning variable defined by default, but I suspect that mongoose would create it if it didn't find it... bad assumption?)

EDIT: Sorry my simplified example had an error in it.

Upvotes: 7

Views: 11472

Answers (2)

Brett Wagner
Brett Wagner

Reputation: 1154

I solved this problem by adding versioning fields to my imported dataset and modifying the schema to associate it with versionKey.

http://mongoosejs.com/docs/guide.html#versionKey

I do wonder, however if there isn't a setting that lets mongoose add the default versionkey (__v) to data that lacks it.

Upvotes: 4

Terry
Terry

Reputation: 14219

You are trying to assign the testSchema to the user object instead of the userSchema so it is looking for an document type that hasn't been created.

Update the user assignment to the following:

var user = mongoose.model('User', userSchema);

I would suggest you follow the guides if you aren't sure what you're doing.

Upvotes: 0

Related Questions