有没有办法在mongoose中重用另一个模式中的模式文档属性?

时间:2018-01-22 07:50:29

标签: node.js mongodb mongoose mongoose-schema

我有两个具有重复createdmodified属性的模式。 mongodb中有没有办法重复使用它而不是一遍又一遍地重复相同的代码?似乎找不到谷歌搜索这个的正确短语。

管理架构

import mongoose from 'mongoose';

const AdminSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  companyId: {
    id: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
  },
  created: {
    at: {
      type: Date,
      default: Date.now,
    },
    by: String,
  },
  modified: {
    at: {
      type: Date,
      default: Date.now,
    },
    by: String,
  },
});

export default mongoose.model('Admin', AdminSchema);

AdminPermissions Schema

import mongoose from 'mongoose';

const AdminPermissionsSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  companyId: {
    id: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
  },
  label: String,
  description: String,
  created: {
    at: {
      type: Date,
      default: Date.now,
    },
    by: String,
  },
  modified: {
    at: {
      type: Date,
      default: Date.now,
    },
    by: String,
  },
});

export default mongoose.model('AdminPermissions', AdminPermissionsSchema);

1 个答案:

答案 0 :(得分:2)

Mongoose为您提供了在使用createdAtupdatedAt属性创建或更新期间时间戳您的文档的选项。这样做而不是使用createdmodified

const AdminSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  companyId: {
    id: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
  },
  createdBy: String,
  modifiedBy: String,
}, {timestamps: true}); //this is required

export default mongoose.model('Admin', AdminSchema);

分别处理createdBymodifiedBy。您可以为所有模式声明添加时间戳,如上所述。