英文:
Go mgo new record?
问题
使用mgo
库是否可以检测我是在处理新记录还是旧记录?
在Rails ActiveRecord中,可以使用object.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?
答案1
得分: 1
在mgo中,没有新/旧记录的概念。就驱动程序而言,它只是内存中的数据。你可以从数据库中加载数据到内存值中,可以在多个内存值中加载数据,并且可以将其保存回数据库,可以使用相同的id或不同的id保存,甚至可以在不同的会话下将其保存到完全不同的数据库中。驱动程序只会执行被要求执行的操作。
应用程序可以通过向结构体添加一个字段并根据需要设置该字段来实现自己的新/旧概念。可以将该字段设置为未导出的,或者使用字段标签bson:"-"
来防止mgo存储该字段。
如果应用程序始终依赖于数据库来分配文档ID,则可以通过检查ID字段来确定文档是新的还是旧的。
英文:
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.
答案2
得分: 0
显然不是。
从mgo的代码来看,我没有看到任何"saved"函数,与ActiveRecord::Persistence.new_record?
文档相比:
如果这个对象还没有保存过,返回true - 也就是说,数据存储中还没有这个对象的记录;否则返回false。
我在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:
而且查找任何IsXxxx()
也没有找到相关的内容(主要是IsMaster
或IsDup
)
英文:
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
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论