You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MEAN Stack下MongoDB数据模型设计咨询:ID类型与FA存储结构

MongoDB Schema Design for MEAN Stack: ID Types & Embedded Array Structure

Great questions—let's break them down one by one based on your charting and query needs.

问题一:自动创建字符串类型的_id

Absolutely, you can set up your schemas to automatically generate string-based _id values, and there are practical benefits to doing so (like smoother frontend handling and cross-system compatibility). Here's how to implement it:

MongoDB uses ObjectIds by default, but string IDs eliminate the need to call .toString() when passing IDs between frontend/backend or integrating with other systems. To auto-generate unique string IDs:

  1. Use a UUID library (most reliable for global uniqueness):
    First install the uuid package:

    npm install uuid
    

    Then update your schema:

    const { v4: uuidv4 } = require('uuid');
    
    var FASchema = new Schema({
      _id: { type: String, default: uuidv4 }, // Auto-generate unique UUID string
      Timestamp: Date,
      ProgBW: Number,
      // ... rest of your FA fields
    });
    
    var FPSchema = new Schema({
      _id: { type: String, default: uuidv4 }, // Apply the same logic to FP if needed
      Demonstrator: Number,
      erstellt: { type: Date, default: Date.now },
      von: Date,
      bis: Date,
      FAs: [{ type: String, ref: "FA" }] // Update ref type to match FA's _id (string)
    });
    
  2. Custom string ID generator (if you don't need UUID-level uniqueness):
    You can create your own rule, like combining timestamps and random strings:

    _id: {
      type: String,
      default: () => `${Date.now().toString()}${Math.random().toString(36).slice(2, 11)}`
    }
    

Important notes:

  • Always ensure your string IDs are unique—MongoDB will throw an error if you try to insert a duplicate _id.
  • String IDs perform just as well as ObjectIds in queries; MongoDB optimizes string indexes effectively.

问题二:FP集合中FAs字段的结构设计

For your charting use case (extracting sequences of fields like Timestamp and negGesEnergie), a document array structure is far better than a field-grouped array structure. Let's break why:

This is the format you mentioned first:

FAs: [
  { Timestamp: Date, negGesEnergie: Number, /* other FA fields */ },
  { Timestamp: Date, negGesEnergie: Number, /* other FA fields */ }
]

Benefits for your workflow:

  1. Intuitive data extraction: Getting chart-ready sequences is straightforward with JavaScript's map()—no messy index matching:

    // Extract x-axis (Timestamps) and y-axis (negGesEnergie values)
    const xAxis = fp.FAs.map(fa => fa.Timestamp);
    const yAxis = fp.FAs.map(fa => fa.negGesEnergie);
    

    This code is readable, maintainable, and ensures each timestamp is paired with the correct energy value (since all fields for a single FA are tied together in one document).

  2. Better scalability: If you later need to add more FA fields to your charts (like ProgBW), you just add the field to the embedded document and update your map() call—no changes to the FP schema required.

  3. Atomic data structure: Each FA instance is a self-contained document, which aligns with MongoDB's document-oriented design principles. This makes it easier to query individual FA instances within the array if needed later.

The format where fields are split into separate arrays ({ Timestamp: [...], negGesEnergie: [...] }) has critical drawbacks:

  • Risk of data misalignment: You have to guarantee every array has the exact same length and order. If one FA instance is missing a field or inserted out of order, your chart data will be completely wrong.
  • Poor maintainability: Adding a new FA field requires modifying the FP schema to add a new array, which is tedious and error-prone.
  • Clunky single-FA queries: To get all fields for one FA, you'd have to fetch the Nth element from every array—code that's hard to read and debug.

Bonus: Embedded vs. Referenced FAs

You currently have FAs as a referenced array (ref: "FA"). If your FA data is static or rarely updated, embedding the full FA documents directly into FP will save you from having to use populate() during queries, making data extraction faster. If FA data is frequently updated, keeping them as references is better—you only update the FA document once, and all FP references will reflect the change.


内容的提问来源于stack exchange,提问作者MarcL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:02:51