kmilo93sd
kmilo93sd

Reputation: 901

Save entity with id created in code, mongoose

How can I do to pass the id of a document from outside and not that mongoose generates it? I need the objects to be stored with the id I tell them, but mongoose overwrites it and saves it with the one he wants. I tried several ways now and nothing happens.

It is an entity that I am distributing through events in several databases, so I need it to be stored with the id I want to maintain the integrity of the data.

Now I have this and it says "document must have an _id before saving", but the id I have already put it, does not recognize it. The scheme is like this:

const schema = new Schema({
_id: { type: String },
name : { type: String },
});

I also tried with this, and the error is the same:

const schema = new Schema({
    _id:  { type : String },
    name : { type: String },
},
{
    _id: false
});

I am passing the object like this:

Item.create({ _id: 'my uuid here', name: 'something' });

but when it is saved it remains with the id generated by mongoose replacing mine, that is, it changes it to me with a _id: '5twt563e3j5i34knrwnt43w'

Upvotes: 0

Views: 687

Answers (2)

Julien TASSIN
Julien TASSIN

Reputation: 5212

Your syntax should work, but sometimes mongoose acts weird.

You can try this syntax (works on my project) :

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

Upvotes: 1

Elvis
Elvis

Reputation: 1143

Instead of using a random uuid, you need to use a mongoDB objectID. Mongoose can also create that,

var mongoose = require('mongoose'); var id = mongoose.Types.ObjectId();

Store this id in the collection,

Item.create({ _id: id, name: 'something' });

Upvotes: 0

Related Questions