Home > OS >  How to make a model's property a specific type?
How to make a model's property a specific type?

Time:12-29

I have the following model:

const mongoose = require("mongoose");
const ChannelDataPayload = require("../models/channelDataPayload");

const channelDataSchema = mongoose.Schema({
  channelId: { type: String, required: true },
  payload: { type: [Object], required: true },
 // payload: { type: [ChannelDataPayload], required: true }, // does not work
  createdAt: {type:Date, required:true},
});

module.exports = mongoose.model("ChannelData", channelDataSchema);

I am trying to make this model require a payload of type ChannelDataPayload but I cant get it to work

here is the ChannelDataPayload model:

const mongoose = require("mongoose");

const channelDataPayloadSchema = mongoose.Schema({
  name: { type:String, required:true },
  value: { type:String, required:true },
});

module.exports = mongoose.model("ChannelDataPayload", channelDataPayloadSchema);

is there anyway of doing this?

ex: the data on each channelDataSchema record should have a property 'payload' that holds an array of key value pairs {name:string,value:string}

CodePudding user response:

The one you need is similar to a join in relational databases.

According to mongoose's documentation:

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

All you should do is to change your code to something like this:

const { Schema } = mongoose;

const channelDataSchema = mongoose.Schema({
  channelId: { type: String, required: true },
  payload: [{ type: Schema.Types.ObjectId, ref: 'ChannelDataPayload' }],
  createdAt: {type:Date, required:true},
});

  • Related