Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a selfdefined ObjectId and avoiding double entries in Mongoose

I am getting 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 store an object:

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

The object is stored fine in the "products" collection, but the id from the JSONProduct is replaced by a MongoDB created value:

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

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

like image 867
Thomas Avatar asked Apr 05 '11 20:04

Thomas


1 Answers

You are defining an field as an ObjectID, but you are assigning a Number to it. To create an ObjectID you need to do something like:

new ObjectId('something');

However, in your case this is probably not the best idea. Define your model like this:

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

You can specify unique on a field to create a unique index for that field.

like image 93
kcbanner Avatar answered Sep 30 '22 16:09

kcbanner