---
title: "非mongodb数据库如何使用mongodb生成的主键id"
author: "hnus"
date: "2015-03-04T18:57:00Z"
tags: []
slug: "mongodb-mongodb-id"
draft: false
lastmod: "2015-05-11T11:49:46Z"
id: 2210124
url: "https://hnus.iteye.com/blog/2210124"
---

场景：由于某种原因没有选择使用mongodb作为数据库，但是又在数据库中增加了\_id作为主键

问题：

1 如何自动生成\_id

2 如何在保存对象的时候设置\_id

生成\_id的解决办法：

Gemfile 中增加

gem "mongoid", "~&gt; 4.0.0"gem "bson\_ext"

在model中增加如下代码

require 'bson'

before\_create do  
self.\_id = BSON::ObjectId.new.to\_s  
end

参考来源：[mongodb/mongo-ruby-driver](https://github.com/mongodb/mongo-ruby-driver/search?utf8=%E2%9C%93&q=ObjectId)