在节点中插入新的 mongo 文档时保存没有 ObjectID 部分的 _id
To save _id without ObjecID part while inserting a new mongo document in node
我注意到,当我在 Meteor 中插入文档时,它会将 _id 保存为 "_id" : "kEdtp42GSupay8tf2"
。
但是当我使用 nodejs 插入时,它在使用以下代码时保存为 "_id" : ObjectId("55e40c30422ba1aa2906f526")
:
MongoClient.connect('mongodb://localhost:3001/meteor', function(err, db) {
if(err) throw err;
var doc = { title: 'post6',
body: "6 Fake St"
};
db.collection('posts').insert(doc, {w:1}, function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
});
我应该如何重构代码以便插入新的 id
s
格式为 "_id" : "kEdtp42GSupay8tf2"
。 ?
参考此 link 中的 idGeneration 选项:
http://docs.meteor.com/#/full/mongo_collection
Meteor 使用字符串值作为 idGeneration。但是如果你想将它更改为默认的 ObjectId 生成,那么你可以设置 idGeneration 选项。
您可以编写一个随机密钥生成器函数并将其设置为_id。
function generateUUID() {
var d = new Date().getTime(),
uuid = 'xxxxxxxxxxxx4xxxxxxxxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c==='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
}
然后用这个设置为_id
。
var doc = { title: 'post6',
body: "6 Fake St"
_id : generateUUID()};
db.collection('posts').insert(doc, {w:1}, function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
我注意到,当我在 Meteor 中插入文档时,它会将 _id 保存为 "_id" : "kEdtp42GSupay8tf2"
。
但是当我使用 nodejs 插入时,它在使用以下代码时保存为 "_id" : ObjectId("55e40c30422ba1aa2906f526")
:
MongoClient.connect('mongodb://localhost:3001/meteor', function(err, db) {
if(err) throw err;
var doc = { title: 'post6',
body: "6 Fake St"
};
db.collection('posts').insert(doc, {w:1}, function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
});
我应该如何重构代码以便插入新的 id
s
格式为 "_id" : "kEdtp42GSupay8tf2"
。 ?
参考此 link 中的 idGeneration 选项:
http://docs.meteor.com/#/full/mongo_collection
Meteor 使用字符串值作为 idGeneration。但是如果你想将它更改为默认的 ObjectId 生成,那么你可以设置 idGeneration 选项。
您可以编写一个随机密钥生成器函数并将其设置为_id。
function generateUUID() {
var d = new Date().getTime(),
uuid = 'xxxxxxxxxxxx4xxxxxxxxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c==='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
}
然后用这个设置为_id
。
var doc = { title: 'post6',
body: "6 Fake St"
_id : generateUUID()};
db.collection('posts').insert(doc, {w:1}, function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});