daryl
daryl

Reputation: 15207

Go mgo new record?

Is it possible to detect whether I'm working with a new record or an old record using mgo?

An example of what I mean is implemented in Rails ActiveRecord:

object.new_record?

Upvotes: 2

Views: 157

Answers (2)

Gustavo Niemeyer
Gustavo Niemeyer

Reputation: 23001

There's no such concept of new/old record with mgo. As far as the driver is concerned, it's just data you have in memory. You can load data from the database in an in-memory value, in multiple in-memory values, and you can save it back, under the same id or a different one, and you can even save it to a completely different database under a different session. The driver will do only what it is asked to do.

The application can implement its own concept of new/old by adding a field to the struct and setting it as appropriate. Make the field unexported or use the field tag bson:"-" to prevent mgo from storing the field.

If the application always relies on the database to assign the document id, then the application can check the id field to determine if the document is new or old.

Upvotes: 1

VonC
VonC

Reputation: 1328192

Apparently not.

Looking at the code of mgo, I don't see any "*saved*" function, compared to the ActiveRecord::Persistence.new_record? doc:

Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist in the data store yet; otherwise, returns false.

I see in mgo:

C:\Users\vonc\prog\git\mgo>gi saved
gridfs.go:360:// SetChunkSize sets size of saved chunks.  Once the file is written to, it
gridfs.go:361:// will be split in blocks of that size and each block saved into an
txn/txn.go:360:// Saved documents are in the format:

And looking for any IsXxxx() doesn't yield anything relevant (mainly IsMaster or IsDup)

Upvotes: 0

Related Questions