求指定MongoDB文档对应的Mongoose Schema(Node.js项目)
Hey, here's how you can map your MongoDB document to a Mongoose Schema, with some practical adjustments for data consistency:
Mongoose Schema Implementation
First, let's define the sub-schema for individual scanned products in the CCR array—this keeps repeated structures clean and reusable:
const ScannedProductSchema = new mongoose.Schema({ ScannedDate: { type: Date, required: true // Mark as mandatory if every entry needs this date }, productNumber: { type: String, required: true }, productType: { type: String, required: true, enum: ['CCR'] // Optional: Ensures only "CCR" values are stored here } });
Next, create the schema for the scannedProductArray object, which houses the CCR array:
const ScannedProductArraySchema = new mongoose.Schema({ CCR: [ScannedProductSchema] });
Finally, wrap everything into the main container schema:
const ContainerSchema = new mongoose.Schema({ container_number: { type: String, required: true }, container_Date: { type: Date, // Use this if you want to perform date operations on this field // OR type: String, if you need to retain the raw "2/2/2018" string format required: true }, scannedProductArray: ScannedProductArraySchema }); // Generate the model to interact with your collection const Container = mongoose.model('Container', ContainerSchema);
Quick Notes:
- I added
required: trueto fields that seem essential, but feel free to remove that flag if any fields are optional in your use case. - For
container_Date, converting the string to aDatetype is recommended if you ever need to sort, filter, or calculate based on this date. If you must keep the string format, swap the type toString. - The
enumconstraint onproductTypehelps prevent invalid values from being stored—remove it if you plan to support other product types later.
内容的提问来源于stack exchange,提问作者Mohammad Ahmad Abdullah
相关产品推荐
相关产品推荐

