Javascript 在节点中插入新的mongo文档时保存_id而不保存ObjCID部分

Javascript 在节点中插入新的mongo文档时保存_id而不保存ObjCID部分,javascript,node.js,mongodb,meteor,bson,Javascript,Node.js,Mongodb,Meteor,Bson,我注意到,当我在Meteor中插入文档时,它将\u id保存为“\u id:“kEdtp42GSupay8tf2” 但是,当我使用nodejs插入时,当使用以下代码时,它将另存为“\u id”:ObjectId(“55e40c30422ba1aa2906f526”): MongoClient.connect('mongodb://localhost:3001/meteor', function(err, db) { if(err) throw err; var doc = {

我注意到,当我在Meteor中插入文档时,它将\u id保存为
“\u id:“kEdtp42GSupay8tf2”

但是,当我使用nodejs插入时,当使用以下代码时,它将另存为
“\u 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


格式为“\u id”:“kEdtp42GSupay8tf2”

请参阅此链接中的idGeneration选项:

http://docs.meteor.com/#/full/mongo_collection

Meteor使用字符串值生成IDF。但如果要将其更改为默认ObjectId生成,则可以设置idGeneration选项。

请参阅此链接中的idGeneration选项:

http://docs.meteor.com/#/full/mongo_collection

Meteor使用字符串值生成IDF。但如果要将其更改为默认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;
}
然后使用此设置为
\u 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();
});    

您可以编写一个随机密钥生成器函数并将其设置为_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;
}
然后使用此设置为
\u 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();
});    

\u id
添加到
doc
中的内容中。当然,你需要一些能产生一个的东西。不过,我并不想离开默认的
ObjectId
,因为它与Meteor使用的不同,它包含有用的东西,并且是Meteor中“友好”格式所没有的“单调”(或不断增加)。您可以“训练”Meteor使用
ObjectId
。这比另一种方法简单得多。将
\u id
添加到
doc
中的内容。当然,你需要一些能产生一个的东西。不过,我并不想离开默认的
ObjectId
,因为它与Meteor使用的不同,它包含有用的东西,并且是Meteor中“友好”格式所没有的“单调”(或不断增加)。您可以“训练”Meteor使用
ObjectId
。这比另一种方式简单得多。难道不可能以我在文章中提到的格式保存吗?在这种情况下,您可以在jsondoc var doc={u id:“kEdtp42GSupay8tf2”,title:'post6',body:“6 Fake St”}中指定_id字段;我想让
\u id
自动生成不可能以我在文章中提到的格式保存吗?在这种情况下,可以在jsondoc var doc={u id:“kEdtp42GSupay8tf2”,title:'post6',body:“6 Fake St”}中指定{u id字段;我想自动生成
\u id