Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 220
Brett Wagner Avatar asked Jan 13 '14 19:01

Brett Wagner


1 Answers

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.

like image 104
Brett Wagner Avatar answered Nov 06 '22 21:11

Brett Wagner