具有 inner/nested 数组的节点 JS 模型

Node JS Model with inner/nested array

我对我的 collection 设计有疑问。

当前设计

const customerSchema = mongoose.Schema({
customer_name: {
    type: String
},
purchase_history: [{
    amount: {
        type: Number,
        default: 0
    },
    currency: {
        type: String,
        require: true
    },
    description: {
        type: String
    }
}],
......
});

每次,如果客户购买了新商品,它会将历史推入“purchase_history”。

“purchase_history”的目的是让他们查询自己的历史。

这是个好主意吗?或者如果你有好的想法,请几位免费分享。

谢谢

我创建了 2 个不同的模式,一个用于客户,另一个用于购买。

请按照标准程序将所有服务文件、模型文件、控制器文件保存在单独的文件夹中。

以下为客户模型

customer.model.js

const mongoose = require('mongoose');
let Schema = mongoose.Schema;

const CustomerSchema = mongoose.Schema({
  customer_name: {
    type: String,
  },
});

const customer = mongoose.model('customer', CustomerSchema);
module.exports = customer;

我们的采购模型为:

purchase.model.js

const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const customer = require('./customer.model');

var purchaseSchema = new Schema(
  {
    customerId: { type: Schema.Types.ObjectId, ref: 'customer' },
    amount: {
      type: Number,
      default: 0,
    },
    currency: {
      type: String,
      required: true,
    },
    description: {
      type: String,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model('purchase', purchaseSchema);

在这里,我们可以看到客户数据存储在客户集合中,购买数据存储在购买集合中。

每条购买记录都有一个参考字段'customerId',这是客户的唯一标识符。此字段在购买模型中定义。

可以通过查询customerId字段来获取客户的购买记录。

我们可以创建一个 api 来获取客户的购买:

purchase.service.js

const purchaseModel = require('./purchase.model');

module.exports.getByCustomerId = async (_customerId) => {
  try {
    const purchaseList = await purchaseModel.find({
      customerId: _customerId,
    });
    return purchaseList;
  } catch (err) {
    throw err.message;
  }
};

这里遵循的设计原则是按照高级开发人员的建议避免重复。将相同的值存储在不同的集合中不是好的做法,购买数据存储在客户集合中。