在 Mongoose 中使用自定义的 ObjectId 并避免重复输入
我通过 node.js 中的外部 API 获取 JSON 对象,并希望将它们存储在 MongoDB 中。我定义了一个这样的模型:
var Product = new Schema({
id: ObjectId,
name: String});
现在我尝试存储一个对象:
JSONProduct = { id: 1234, name: 'The Foo Bar' };
product = new Product(JSONProduct);
product.save();
该对象很好地存储在“products”集合中,但是 JSONProduct 中的 id 被 MongoDB 创建的值替换:
{ "id" : ObjectId("119894980274616772006500"), "name" : "The Foo Bar" }
我想使用我的产品 ID 而不是 MongoDB 创建的产品 ID 的主要原因是,我想防止产品的重复条目。我通过 cronjob 触发对外部 API 的调用来获取 JSON Product 对象,包括已经存在的 API。也许还有另一种更好的方法来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将一个字段定义为 ObjectID,但为其分配一个数字。要创建 ObjectID,您需要执行以下操作:
但是,就您的情况而言,这可能不是最好的主意。像这样定义模型:
您可以在字段上指定
unique
来为该字段创建唯一索引。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:
However, in your case this is probably not the best idea. Define your model like this:
You can specify
unique
on a field to create a unique index for that field.在您提到的问题中,
该对象很好地存储在“products”集合中,但 JSONProduct 中的 id 被 MongoDB 创建的值替换:
{ "id" : ObjectId("119894980274616772006500"), "name" : "The Foo Bar" }
但我认为它的创建方式为:
{ "_id" : ObjectId("119894980274616772006500"), "name" : "The Foo Bar" }
另外,您可以通过名称“_id”将产品 ID 传递到字段,然后 mongo 将不会创建任何单独的 ID,并且不会接受重复的值,并且它'将自动为该字段建立索引。
但请确保将产品 id 的唯一值推送到 _id。
In the question you've mentioned,
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" }
But I think the it is created as:
{ "_id" : ObjectId("119894980274616772006500"), "name" : "The Foo Bar" }
Also, you can pass in your product id to field by name "_id", then mongo will not create any separate IDs and it'll not accept duplicate values and it'll have indexing automatically for that field.
But make sure you push unique values of product id to _id.