mongoose:适当地devise一个关系模式

我试图在我的mongodb / monogoose数据库中的几个对象之间build立一些关系数据,使用引用(在属性中存储ID)。我写了我已经实现的和我的缺点。 这是一个广阔的职位,请阅读我的TL; DR之前阅读所有内容。 一些代码的高级答案也是可以接受的。

我在我的Mongoose数据库中有以下模式:

用户:

UserSchema: { _id: (MongoID) isActive: firstName: lastName: email: phone: role: hash: address: } 

车辆:

 VehicleSchema: { _id: (MongoID) internal_id: (linking id) metadata: (product name, product description) } 

值:

 ValueSchema: { _id: (MongoID) internal_id: (linking id) todayPrice: xxx.xx history [ {...}, {...}, {...}] } 

每个user都有一个garage ,他们可以存放vehiclestypesVehicleSchemavehicle关系需要以下function:

  1. user可以将vehicles CRUD到他的garage (一次一个)。

build议; 添加(C ** D)以下到UserSchema

garage: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Vehicle' }]

 UserSchema.methods.addToGarage= function (id) { if (this.garage.indexOf(id) === -1) { this.garage.push(id); } return this.save(); }; UserSchema.methods.removeFromGarage= function (id) { this.garage.remove(id); return this.save(); }; UserSchema.methods.isInGarage= function (id) { return this.garage.some(function (vehicleId) { return vehicleId.toString() === id.toString(); }); }; 

我在为我的garage CRUD的“R”(读)时遇到了麻烦,但我有一个出发点:

 UserSchema.methods.viewGarage= function (id) { return this.garage; // only Ids? how do I include the actual document? }; 

我想也许在user's garage使用车辆的_id属性,并使用它们来匹配Vehicles.find({})查询。

  1. 一个pipe理员应该能够运行一个查询,可以得到在garagesvehicle _id的频率。

查询:从所有usersgarages中获取所有vehicles并统计频率。 在车库中返回一个(sorting)的vehicle和时间arrays。

起点 – 使用聚合查询:

  User.aggregate([ { $lookup: { from: "vehicle", localField: "garage", // ?? attempt: garage.forEach() foreignField: "_id", as: "vehicle" } } ]) 

在这里我坚持从users --> users.garage[] --> vehicle --> vehicle.internal_id ,然后计数_ids到一个频率图。

  1. vehiclevalue是共享相同的internal_id键/值对的对象。 (这些对象使用$lookup进行合并)。这就是重要的地方。 如果价格发生变化,pipe理员可以运行更新Values的脚本:

     Values.find({}).then(docs => { docs.forEach(value => { request((myUrl, value) => { // update logic here if (update) { // if there is an update value.save(); // VALUE SCHEMA WAS UPDATED } }); }}); 

ValueSchema更新时 – >我需要通知每个用户有一个值的变化。 为了做到这一点,我需要一个列表,他们的garage,有更新的vehicle.internal_id garage, [user – > garage [] – > vehicle < – > value],并且能够遍历该列表。 我在创build这个用户列表时遇到了麻烦,他们的garage中的Vehicle Value已更新。

TL; DR:

  1. 实现价值<车辆< – >车库< – >用户关系的最佳实践是什么?

  2. 如何通过参考返回存储在车库中的车辆?

  3. 我怎样才能得到保存在车库里的车辆的频率? (把车库想成最爱列表)

  4. 我怎样才能创build一个与这些关系的通知系统? (通知用户更新,ex this.sendEmail(user.email))