Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用代码mongoose中创建的id保存实体_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 使用代码mongoose中创建的id保存实体

Node.js 使用代码mongoose中创建的id保存实体,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,如何从外部传递文档的id,而不是mongoose生成的id? 我需要用我告诉他们的id来存储对象,但是mongoose会覆盖它并用他想要的id保存它。我现在尝试了几种方法,但什么也没发生 它是一个通过多个数据库中的事件分发的实体,因此我需要将它与我希望保持数据完整性的id一起存储 现在我有了这个,它说文档在保存之前必须有一个_id,但是我已经放好的id不能识别它。 这个计划是这样的: const schema = new Schema({ _id: { type: String }, name

如何从外部传递文档的id,而不是mongoose生成的id? 我需要用我告诉他们的id来存储对象,但是mongoose会覆盖它并用他想要的id保存它。我现在尝试了几种方法,但什么也没发生

它是一个通过多个数据库中的事件分发的实体,因此我需要将它与我希望保持数据完整性的id一起存储

现在我有了这个,它说文档在保存之前必须有一个_id,但是我已经放好的id不能识别它。 这个计划是这样的:

const schema = new Schema({
_id: { type: String },
name : { type: String },
});
Item.create({ _id: 'my uuid here', name: 'something' });
我也试过这个,错误是一样的:

const schema = new Schema({
    _id:  { type : String },
    name : { type: String },
},
{
    _id: false
});
我正在通过这样的物体:

const schema = new Schema({
_id: { type: String },
name : { type: String },
});
Item.create({ _id: 'my uuid here', name: 'something' });

但是当它被保存时,它会保留由mongoose生成的id来代替我的id,也就是说,它会用一个“5twt563e3j5i34knrwnt43w”将它更改为“我”

而不是使用随机uuid,您需要使用mongoDB objectID。猫鼬也能创造出

var mongoose=需要“mongoose”; var id=mongoose.Types.ObjectId

将此id存储在集合中


创建{{u id:id,name:'something'}

您的语法应该是有效的,但有时候猫鼬的行为很奇怪

您可以尝试在我的项目中使用以下语法:

const item = new Item({ name: 'something' });    
item._id = 'my uuid here';
await item.save();

我使用了您提供的确切代码,它工作了存储在db中的id是:my uuid here:所以我的建议是:创建一个新的空白项目,并使用此代码检查它是否工作。最好说您更好,而不是您需要,因为mongoose也可以使用自定义的_id。