【问题标题】:Using cuid to replace mongoose ObjectIds使用 cuid 替换 mongoose ObjectIds
【发布时间】:2017-02-14 04:01:05
【问题描述】:

我正在考虑使用 cuid (https://www.npmjs.com/package/cuid) 来替换 mongoose 的自然生成的 objectid,这样我的模型中的 _id 会得到一个 cuid 而不是生成的。

问题:

  1. 你是如何做到这一点的
  2. 有没有副作用
  3. 这将如何影响人口??

1 就这么简单:

import mongoose from 'mongoose';
import cuid from 'cuid';

const Schema = mongoose.Schema;

export const departmentSchema = new Schema({
  _id: { type: 'String', default: cuid(), required: true },
  name: { type: 'String', required: true },
  sector: { type: 'String', required: true },
});

??

谢谢

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    我已经成功使用以下方法来使用 CUID 而不是 _id:

    import mongoose from 'mongoose';
    import cuid from 'cuid';
    
    const gymSchema = new Schema({
      _id: { type: 'String', required: true, default: cuid },
    }):
    

    不同之处在于我只是传递函数,而您调用函数。我一开始就犯了这个错误……

    我可以确认人口按预期工作,但我无法回答的问题是是否有任何副作用。可能,更重要的是,你为什么要这样做。 mern.io 使用 CUID 而不是 ObjectId,但他们在另一个领域做得很尴尬。我不知道为什么 ObjectIds 不合适。有人吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 2020-07-21
      • 2017-02-22
      • 2016-10-14
      • 2020-05-18
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      相关资源
      最近更新 更多