简体   繁体   English

如何使用Angular流星为MongoDB中的嵌套对象生成唯一的ID?

[英]How to generate a unique id for a nested object in MongoDB using Angular-meteor?

So, I have the following code in my app.js: 因此,我的app.js中包含以下代码:

Countries = new Mongo.Collection('countries');

// Some skipped code

$scope.addRegion = function(newRegion) {
  $scope.country.regions.push(
    {
      name: newRegion.name,
      createdAt: new Date()
    }
  );
};

This successfully adds a new region object in the array and is persistent in the database. 这样可以成功地在数组中添加一个新的区域对象,并在数据库中保持不变。 Although it has no "_id" field. 尽管没有“ _id”字段。

How can I generate a unique id for each insertion? 如何为每次插入生成唯一的ID? (and by unique, I mean unique in the database) (所谓唯一,是指数据库中唯一)

Use the random package - specifically Random.id . 使用random包-特别是Random.id From the docs : 文档

Returns a unique identifier, such as "Jjwjg6gouWLXhMGKW", that is likely to be unique in the whole world. 返回唯一标识符,例如“ Jjwjg6gouWLXhMGKW”,在全球范围内很可能是唯一的。 The optional argument n specifies the length of the identifier in characters and defaults to 17. 可选参数n以字符为单位指定标识符的长度,默认为17。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM