猫鼬模式中嵌套对象中的元素需求如何

时间:2019-06-07 10:48:33

标签: javascript node.js mongoose schema nestjs

创建模式我需要一些嵌套对象始终位于数据发布中,以保存在数据库中。

我尝试过这种方式来创建2个模式,并且需要对象valid,但是我还需要valid.fromvalid.to,并且这种方式不起作用。

import * as mongoose from 'mongoose';

const LicenseTime = new mongoose.Schema({
  from: { type: Date, required: true },
  to: { type: Date, required: true },
});

export const LicenseSchema = new mongoose.Schema({
  customer: { type: String, required: true },
  appId: { type: String, required: true },
  purchaseDate: { type: Date, required: true },
  valid: { type: LicenseTime, required: true }
});

2 个答案:

答案 0 :(得分:0)

但是我能尝试的,您的示例有效。我使用了以下模式:

import { Schema } from 'mongoose';

const LicenseTime = new Schema({
  from: {
    type: Date,
    required: true,
  },
  to: {
    type: Date,
    required: true,
  },
},
{
  _id: false, // Used so mongoose/mongo doesn't create id
  id: false, // Used so mongoose/mongo doesn't create id
});

export const LicenseSchema = new Schema({
  customer: {
    type: String,
    required: true,
  },
  appId: {
    type: String,
    required: true,
  },
  purchaseDate: {
    type: Date,
    required: true,
  },
  valid: {
    type: LicenseTime,
    required: true,
  },
});

当我尝试保存除以下内容以外的其他内容时,请使用此架构:

{
  customer: 'example customer',
  appId: 'example appId',
  purchaseDate: new Date(),
  valid: {
    to: new Date(),
    from: new Date(),
  },
}

保存失败。

示例:如果我尝试保存:

{
  customer: 'example customer',
  appId: 'example appId',
  purchaseDate: new Date(),
  valid: {
    to: new Date(),
  },
}

代码失败,并显示:

  

[嵌套] 8895-06/12/2019,下午1:42 [ExceptionsHandler] Cat验证失败:有效。来自:路径from是必需的。,有效:验证失败:来自:路径{{1 }} 是必须的。 + 829ms   [0] ValidationError:Cat验证失败:valid.from:路径from是必需的。,valid:验证失败:from:路径from是必需的。   [0]在新的ValidationError(/home/adrian/work/try/node_modules/mongoose/lib/error/validation.js:30:11)   [0]在model.Document.invalidate(/home/adrian/work/try/node_modules/mongoose/lib/document.js:2260:32)   [0]在SingleNested.Subdocument.invalidate(/home/adrian/work/try/node_modules/mongoose/lib/types/subdocument.js:147:18)   [0]位于p.doValidate.skipSchemaValidators(/home/adrian/work/try/node_modules/mongoose/lib/document.js:2109:17)   [0]位于/home/adrian/work/try/node_modules/mongoose/lib/schematype.js:981:9   [0]在processTicksAndRejections(internal / process / task_queues.js:82:9)

最后,我正在使用以下依赖项:

from

答案 1 :(得分:0)

您需要这样写LicenseSchema

export const LicenseSchema = new mongoose.Schema({
  customer: { type: String, required: true },
  appId: { type: String, required: true },
  purchaseDate: { type: Date, required: true },
  valid: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "LicenseTime", 
    required: true
  }
});

顺便说一句,这可能是Reference in mongoose schema的重复

让我知道是否有帮助