【问题标题】:To save _id without ObjecID part while inserting a new mongo document in node在节点中插入新的 mongo 文档时保存没有 ObjecID 部分的 _id
【发布时间】:2015-08-31 17:29:33
【问题描述】:

我注意到,当我在 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();
    });
});

我应该如何重构代码以便插入新的ids

格式为"_id" : "kEdtp42GSupay8tf2"。 ?

【问题讨论】:

  • _id 添加到doc 的内容中。当然,您将需要一些可以生成的东西。不过,我不会那么热衷于摆脱默认的ObjectId,因为它与 Meteor 使用的不同,它包含有用的东西并且也是“单调”(或不断增加),而流星中的“友好”格式不是。你“可以”总是“训练” Meteor 使用ObjectId。这比反过来做要简单得多。

标签: javascript node.js mongodb meteor bson


【解决方案1】:

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

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

Meteor 使用字符串值作为 idGeneration。但是如果你想将其更改为默认的 ObjectId 生成,那么你可以设置 idGeneration 选项。

【讨论】:

  • 不可以按照我帖子里提到的格式保存吗?
  • 这种情况下,可以在jsondoc中指定_id字段 var doc = { _id: "kEdtp42GSupay8tf2", title: 'post6', body: "6 Fake St" };
  • 我想自动生成_id
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2015-02-09
    • 1970-01-01
    • 2014-09-08
    • 2022-08-18
    相关资源
    最近更新 更多