首页 > 解决方案 > 如何在猫鼬中结合两个模型属性生成唯一的密钥哈希

问题描述

我正在尝试生成hash两个模型属性的组合。

我有这样的架构

const BlogPost = new Schema({
  id: { type: String, required: true, unique: true },
  empid: String,
  date: Date
}); 

我想创建一个独特idhash组合 。如果生成empid and date相同的话,我会出错。我们可以组合生成吗?hashgivesuniqueempid and date

如果我们通过,将生成相同的哈希empid and date?然后它给了我错误

这是我的代码 https://codesandbox.io/s/lively-tree-hd0fo

try {
    var blog = new BlogPostModel({
      empid: "test123",
      date: "19-Jul-2019"
    });
    console.log("before save");
    let saveBlog = await blog.save(); //when fail its goes to catch
    console.log(saveBlog); //when success it print.
    console.log("saveBlog save");
  } catch (error) {
    console.log(error);
  }

标签: javascriptnode.jsmongodbmongoose

解决方案


我以前为此使用过uuid库。Node 也有一个内置的md5 哈希库


推荐阅读