使用Javascript手动插入ObjectId

Manually insert ObjectId with Javascript

本文关键字:插入 ObjectId Javascript 使用      更新时间:2023-09-26

我得到了一个名为"article"的对象,我直接将其插入MongoDB。但我对其中一个子对象有问题:

article.tags = ObjectId("' + tags + '");
//This doesn't work because: ObjectId is not defined
article.tags = "ObjectId("' + tags + '")"; 
//This works half-way because: ObjectId gets inserted as a custom value "ObjectId"
// inside commas, not as a true
// ObjectId, therefore my application won't interpret it.

我曾想过在应用程序中需要一些mongodb驱动程序,它能工作吗?有没有更干净的方法来处理这个问题?

注意:标记已经在数据库中定义并正确索引,必须以这种方式插入。


也许这只是一个拼写错误:ObjectId!==ObjectID???


您需要ObjectID还是只需要mongodb客户端?

var ObjectID = require('mongodb').ObjectID;

那么你应该做:

var someId = new ObjectID("ABCDEFABCDEFABCDEFABCDEF") // should be 24 byte long