Synchronize mongo databases on different servers

自古美人都是妖i 提交于 2019-12-04 05:24:58

I haven't tried this, but the current MongoDB documents describe a replication set equivalent to master-slave replication:

Deploy Master-Slave Equivalent using Replica Sets

If you want a replication configuration that resembles master-slave replication, using replica sets, consider the following replica configuration document. In this deployment hosts and 1 provide replication that is roughly equivalent to a two-instance master-slave deployment:

{
   _id : 'setName',
   members : [
              { _id : 0, host : "<master>", priority : 1 },
              { _id : 1, host : "<slave>", priority : 0, votes : 0 }
  ]
}

See Replica Set Configuration for more information about replica set configurations.

Use _id instead of id. There is no need to declare it in your model.

if you have plenty of servers

I use on each server a small prehook which creates a controlled unique _id. The mongoose _id is built very logical (https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectIDs-BSONObjectIDSpecification), the digits 0,6 are the machine identifier. I just control these digits because I have multiple servers and I want to assure there is no collusion. If you have just a few, it is probably no risk to not do this. And even in my case I think it is too paranoid.

exports.useProcessId = ()->
  return process.env.INSTANCE_PROCESS_ID? && process.env.INSTANCE_PROCESS_ID.length == 4

exports.manipulateMongooseId = (id) ->
  id = id.toString()
  newId = new ObjectId(id.slice(0,6) + process.env.INSTANCE_PROCESS_ID + id.slice(10,24))
  return newId

schema

mymOdelSchema.pre('save', (next) ->
  data = @
  async.parallel
    myModel: (next)->
      myModelValidator.base(data, next)
    changeMongooseId: (next)->
      if useProcessId && instanceType == 'manager' then processIdConfig.changeMongooseId(data, next) else return next()
    (err)->
      return

 next new Error(err) if err?
      return next()
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!