0

How do I create a model instance from object and let Mongoose know it already exists? I'm loading data from cache, so it is always up to date.

I've tried using

var instance = new SomeModel({ '_id': '...', field1: '...', field2: '...' });

but this way Mongoose thinks it's a new object to be inserted, not already existing one. Calling instance.modifiedPaths() returns ['_id', 'field1', 'field2']. So if I call instance.save() it will try to insert it again and throw a duplicate key error.

What's the proper way to do it?

Sebastian Nowak
  • 5,607
  • 8
  • 67
  • 107

2 Answers2

2

There is a flag that indicates whether the record is new or not, you could override it before calling save:

var instance = new SomeModel({ '_id': '...', field1: '...', field2: '...' });
instance.isNew = false;
instance.save(function(err) { /* ... */ });

In this case, Mongoose will update the record instead of trying to insert it.

This is however weird, are you sure you are not better querying the document from the database using find or some of its variations?

victorkt
  • 13,992
  • 9
  • 52
  • 51
  • The whole idea of caching is NOT querying the database. Thanks for the `isNew` anyway, turns out there's undocumented function `Document.init()` declared right below it. – Sebastian Nowak Mar 04 '15 at 22:41
0

There's undocumented Document.init() function which does exactly that. It accepts a callback as last parameter, while in fact is currently useless - current implementation isn't asynchronous and the callback will never receive an error. However it may change in the future, so the recommended solution is:

function load (model, data, callback)
{
    var w = new model();
    w.init(data, {}, function (err)
    {
        if (err) return callback(err);
        callback(null, w);
    });
}
Sebastian Nowak
  • 5,607
  • 8
  • 67
  • 107