在节点中插入新的mongo文档时,保存没有ObjecID部分的_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"
。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();
});
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 通过id和class属性获取元素
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 使用当前日期生成随机id
- Javascript-ID冲突的几率
- Href:当前DIV中的目标ID
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- Javascript复选框函数:;缺少:在属性id之后"
- Twitter引导程序Typeahead-Id&标签
- 如何与特定ID交谈
- chart.series[id].remove()无法刷新高位图表/高位股票中其他系列的图例属性
- 如何在速度模板中获取LiferayPortlet实例id
- 谷歌地图可以't添加正确的标记ID
- 识别没有ID或特定属性的对象