从官方mongoose v3.8.7的手册中看到关于Schema的_id属性,发现这个属性在new一个模型的时候就已经生成了,这个时候根本就没有和MongoDB通信!
我好奇mongoose是如何生成这个_id的值的,它能保证唯一性么?
另外,官方提到可以关闭这个特性,但是
var schema = new Schema({ name: String }, { _id: false });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { name: 'mongodb.org' }
// MongoDB will create the _id when inserted
p.save(function (err) {
if (err) return handleError(err);
Page.findById(p, function (err, doc) {
if (err) return handleError(err);
console.log(doc); // { name: 'mongodb.org', _id: '50341373e894ad16347efe12' }
})
})
实际测试发现根本就不会save成功,会提示:
[Error: document must have an _id before saving]
请问如何关闭_id后实现保存?
Each document must have an _id and it cannot be repeated.
If you turn off this feature, you have to create an _ID yourself
So, of course you can’t save it.
First of all, _id is a globally unique object identifier in mongodb, and there will be no duplicates.
The value of _id can also be defined by yourself. If no definition is added, the system will use the 12-byte object identifier generated by default
Professional speaking, it should be:
4323原则
4-digit Unix timestamp
3-digit machine code
2-digit process number
3-digit counter code, starting from a random number
Mongod will generate an ID based on the results obtained above! ~