在节点中插入新的mongo文档时,保存没有ObjecID部分的_id

To save _id without ObjecID part while inserting a new mongo document in node

本文关键字:ObjecID id 保存 插入 节点 mongo 文档      更新时间:2023-09-26

我注意到,当我在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"。div ?

在此链接中引用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();
});