简体   繁体   English

如何使用 Node js 和 MongoDB 关联两个模型?

[英]How do i relate two models using Node js and MongoDB?

So i'm making a simple game store like steam, i have a user model and a games model, i need to make a games library and have each user have their own library with games they choose from the store, how do i make it so when a user chooses a game that game is saved into their library using Node js and MongoDB?所以我正在制作一个像 Steam 这样的简单游戏商店,我有一个用户 model 和一个游戏 model,我需要制作一个游戏库,并让每个用户都有自己的游戏库,其中包含他们从商店中选择的游戏,我该如何制作因此,当用户选择游戏时,该游戏会使用 Node js 和 MongoDB 保存到他们的库中?

You can create an array of games in user model and whenever user add a game, the id of that game will be stored in the user model.您可以在用户 model 中创建游戏数组,每当用户添加游戏时,该游戏的 id 将存储在用户 model 中。 And then you can retrieve the data by using that id.然后您可以使用该 ID 检索数据。

If you have a Game and a User model, you can simply create an array of references to the Game model inside the User model.如果你有一个游戏和一个用户 model,你可以简单地在用户 model 中创建一个对游戏 model 的引用数组。 Like this:-像这样:-

User.js用户.js

const userSchema = mongoose.Schema({
  // Other user stuff
  games = [{
    type : mongoose.Schema.Types.ObjectId,
    ref : 'Game'
  }]
});

module.exports = mongoose.model('User', userSchema);

Game.js游戏.js

const gameSchema = mongoose.Schema({
  // Other game fields
  users = [{
    type : mongoose.Schema.Types.ObjectId,
    ref : 'User'
  }]
});

module.exports = mongoose.model('Game', gameSchema);

Thereafter, you can simple push a game document to a user document using user.games.push(game)此后,您可以使用user.games.push(game)简单地将游戏文档推送到用户文档

Make sure that your 'ref' field has the same name as the model of the object you want to refer to.确保您的“参考”字段与您要引用的 object 的 model 名称相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM