为什么我不能在我的NodeJS应用程序中使用stringuuid作为自定义的MongoDB _id?

我正在开发一个NodeJS应用程序与MongoDB数据库(使用本地MongoDB的NodeJS驱动程序),并希望使用一个string作为我的主键。

当_id是一个string时,这个插入失败了:

collection.insert({_id : "customId", name : "sampleName", email : "sampleEmail"}, {}, function(err, result) { if (err) { res.send({msg : err}); } else { res.send({msg : 'SUCCESS'}); } }); 

这段代码在我的NodeJS应用程序中。 当我通过我的数据库上的mongo shell命令尝试相同的插入时,它工作正常。

我知道MongoDB主键的自定义_id字段必须保证是唯一的。 我打算在我的代码中使用uuidstring,但没有string_id似乎工作。 我在这里阅读https://docs.mongodb.org/manual/core/document/#field-names _id必须是唯一的,可以是除数组以外的任何types。 我也回顾了这个问题在MongoDB中创build自定义对象ID是相似的,但它还没有解决我的问题。 为什么我不能使用string作为自定义_id字段?

编辑:错误消息说:“[错误:parameter passing必须是一个12字节的string或24个hex字符的string]”

编辑2:

这是我的完整代码:

 router.post('/addcontact', function(req, res) { var db = req.db; var newContact = req.body; var newContactId = uuid.v4(); var newContactId = String(newContactId); //newContact['_id'] = newContactId; var collection = db.get('contactlist'); console.log("about to do insert"); try { collection.insert({_id : '4BF6EFC6-1682-4A40-A0DE-8CD104AC92D3', name : "testName", email : "testEmail", phone : "testPhone"}, {}, function(err, result){ if (err) { res.send({msg : err}); } else { res.send({msg : 'SUCCESS'}); // log operation in log file with Kafka var producer = req.kafkaProducer; var payload = {topic : 'logging', messages: 'POST /addcontact id:' + newContactId + ' ' + newContact["name"]}; producer.send([payload], function (err, data) { // console.log(data); }); } }); } catch (err) { console.log(err); } }); 

请注意,我实际上并没有使用http POST中的newContact信息,只是试图让示例插入工作。

这里是控制台打印出来的错误:

 about to do insert [Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters] POST /contacts/addcontact - - ms - - 

这是我的package.json与依赖关系:

 { "name": "NodeApp2", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "async": " . . ", "body-parser": "~1.13.2", "cookie-parser": "~1.3.5", "couchbase": "^2.1.2", "debug": "~2.2.0", "express": "~4.13.1", "jade": "~1.11.0", "kafka-node": " . . ", "kerberos" : " . .*", "mongodb": "2.0.49", "monk": "~1.0.1", "morgan": "~1.6.1", "node-gyp": "^3.1.0", "serve-favicon": "~2.3.0" } 

所以你实际上并没有直接使用mongodb ,而是通过monkdb.get('contactlist')把它拿走了), monk自动将_id转换为ObjectId ,这就是为什么你会得到这个错误。

看起来这种行为不能被closures ,所以你可能不得不将你的代码迁移到mongodb