使用MongoDB(Mongoose)和.populate()实现一对多

ivqmmu1c  于 2023-01-17  发布在  Go
关注(0)|答案(1)|浏览(160)
我在做什么

我试图通过playerId返回一个player,并在其模式中返回每个对象的所有ref项,在本例中,我专门讨论了player清单。
如何返回所有引用项及其属性?
在我的服务文件中,我将使用以下选项获取播放器:

/**
 * Get a player by playerId
 * @param playerId
 * @returns {Promise<*>}
 */
module.exports.getPlayer = async (playerId) => {
  return await Player.findOne({ playerId: playerId }).populate('inventory');
};
这是我返回的JSON
{
    "success": true,
    "data": {
        "_id": "63bb1f3ec17d33f4d2a87194",
        "playerId": 4183489039,
        "name": "AlanGreyjoy",
        "currency": {
            "copper": 500,
            "silver": 10,
            "gold": 0
        },
        "online": false,
        "inventory": [
            {
                "currentDurability": 0,
                "item": "63ba0c54407456969ba38615",
                "amount": 1,
                "_id": "63bc4fa070eaa247288e3573",
                "createdAt": "2023-01-09T17:32:16.643Z",
                "updatedAt": "2023-01-09T17:32:16.643Z"
            }
        ],
        "bank": [],
        "questTracker": [],
        "friends": [],
        "knownRecipes": [],
        "jobs": [],
        "createdAt": "2023-01-08T19:53:34.903Z",
        "updatedAt": "2023-01-09T17:32:16.643Z",
        "__v": 1
    }
}

如您所见,库存数组中的项没有使用items集合中的ref项填充。
我搜索了又搜索,尝试了很多不同的方法,但都没有效果。
数据库

中确实存在该项目

我的模特

我的玩家. model. js

const mongoose = require('mongoose');
const toJSON = require('../plugins/mongoToJson');

const Schema = mongoose.Schema;

const questTracker = new Schema(
  {
    quest: { type: mongoose.Schema.Types.ObjectId, ref: 'Quest' },
    complete: { type: Boolean, default: false },
  },
  { timestamps: true }
);

const friends = new Schema(
  {
    player: { type: mongoose.Schema.Types.ObjectId, ref: 'Player' },
    isFavorite: { type: Boolean, default: false },
  },
  { timestamps: true }
);

const knownRecipes = new Schema(
  {
    recipe: { type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' },
  },
  { timestamps: true }
);

const jobs = new Schema(
  {
    job: { type: mongoose.Schema.Types.ObjectId, ref: 'Job' },
  },
  { timestamps: true }
);

const inventoryItems = new Schema(
  {
    item: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
    amount: { type: Number, default: 0 },
    currentDurability: { type: Number, default: 0 },
  },
  { timestamps: true }
);

const bank = new Schema(
  {
    item: { type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
    amount: { type: Number, default: 0 },
  },
  { timestamps: true }
);

const playerSchema = new Schema(
  {
    playerId: {
      type: Number,
      unique: true,
      required: true,
    },
    name: {
      type: String,
      required: true,
      unique: true,
    },
    currency: {
      type: Object,
      default: {
        copper: 500,
        silver: 10,
        gold: 0,
      },
    },
    inventory: [inventoryItems],
    bank: [bank],
    questTracker: [questTracker],
    friends: [friends],
    knownRecipes: [knownRecipes],
    jobs: [jobs],
    online: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

const PlayerModel = mongoose.model('player', playerSchema);

module.exports = PlayerModel;

我的物品. model. js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const toJSON = require('../plugins/mongoToJson');

const vendorPriceSchema = mongoose.Schema({
  copper: {
    type: Number,
    default: 0,
  },
  silver: {
    type: Number,
    default: 0,
  },
  gold: {
    type: Number,
    default: 0,
  },
});

const itemSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
      unique: true,
    },
    assetId: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
    },
    equipDescription: {
      type: String,
    },
    additionalDescription: {
      type: String,
    },
    consumableUseDescription: {
      type: String,
    },
    itemLevel: {
      type: Number,
    },
    requiredLevel: {
      type: Number,
    },
    type: {
      type: String,
      required: true,
    },
    subtype: {
      type: String,
      required: true,
    },
    stamina: {
      type: Number,
    },
    intellect: {
      type: Number,
    },
    criticalStrike: {
      type: Number,
    },
    agility: {
      type: Number,
    },
    mastery: {
      type: Number,
    },
    maxDurability: {
      type: Number,
    },
    vendorPrice: { vendorPriceSchema },
    minDamage: {
      type: Number,
      default: 0,
    },
    maxDamage: {
      type: Number,
      default: 0,
    },
    speed: {
      type: Number,
    },
    maxStack: {
      type: Number,
    },
  },
  { timestamps: true }
);

const ItemModel = mongoose.model('Item', itemSchema);

module.exports = ItemModel;
kt06eoxx

kt06eoxx1#

您可以使用类似于以下内容的内容:

module.exports.getPlayer = async (playerId) => {
  return await Player.findOne({ playerId: playerId }).populate({
      path: "inventory",
      populate: {
        path: "item",
      },
    });
};

相关问题