Domanda

Defined in the Blogpost model.

schema.user = { type: mongoose.Types.ObjectId, ref: 'User' };

Later on when accessing a document matching the model...

// Timestamp of when the user was created.
userDocument._id.getTimestamp();

// Different ObjectId, same value.
blogpostDocument.user.getTimestamp();

Will these timestamps be the same?

The reason why I'm not just testing it myself is that I'm changing the models of my database extremely in order to optimize them and add new fields, and I'm not done changing them yet. So I would prefer to know the implications of this problem before I update all my documents to match the new model.

Thank you!

È stato utile?

Soluzione

ObjectIDs with the same underlying raw value will all have the same timestamp.

var mongoose = require('mongoose');
var o1 = new mongoose.Types.ObjectId();
var o2 = new mongoose.Types.ObjectId(o1.toString());
o1.getTimestamp();
//Fri Jul 26 2013 17:47:17 GMT-0600 (MDT)
o2.getTimestamp();
//Fri Jul 26 2013 17:47:17 GMT-0600 (MDT)

Side note: when defining schemas you need to use mongoose.SchemaTypes.ObjectId not mongoose.Types.ObjectId.

2nd Side note: It is probably best to tread object IDs as opaque strings and if you want to track creation date, track them with dedicated fields. Keep in mind the mongodb object IDs are generated by the drivers external to the database itself and the timestamp are when the object is instantiated in memory, which might be quite a bit before it actually gets sent to the database for storage.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top