Using self-defined ObjectId and avoiding duplicate entries in Mongoose

I get JSON objects through an external API in node.js and want to store them in MongoDB. I defined a model like this:

var Product = new Schema({
        id: ObjectId,
    name: String});

And now I'm trying to save an object:

JSONProduct = { id: 1234, name: 'The Foo Bar' };
product = new Product(JSONProduct);
product.save();

The object is perfectly stored in the "products" collection, but the identifier from JSONProduct is replaced by the value created by MongoDB:

{ "id" : ObjectId("119894980274616772006500"), "name" : "The Foo Bar" }

The main reason I want to use my product identifier over the created MongoDB is because I want to prevent duplicate entries for products. I get JSON Product objects through a cronjob call to an external API, including existing ones. Maybe there is another, better way to do this?

+5
source share
2

ObjectID, Number. ObjectID, - :

new ObjectId('something');

, , . :

var Product = new Schema({
  external_id: {type: Number, unique: true},
  name: {type: String},
});

unique , .

+5

, ,

"", JSONProduct MongoDB: { "id": ObjectId ( "119894980274616772006500" ), "name": "Foo Bar" }

, :

{ "_id": ObjectId ( "119894980274616772006500" ), "name": "Foo Bar" }

, "_id", mongo , , .

, _id.

0

All Articles