简体   繁体   English

猫鼬的关系一对多

[英]Mongoose relationship multiple to one

I have a problem, more precisely i don't understand one thing with monggose and relationship. 我有一个问题,更确切地说,我对mon昧和关系一无所知。

I have one collection "Athletes" : 我有一个“运动员”收藏:

var athletesSchema = mongoose.Schema({
name : String,
regionName : String,
age : Number,
overallScore : Number,
scores : {
    ordinnal : String,
    ordinnal2 : String,
    ordinnal3: String,
    ordinnal4: String,
    ordinnal5:String
}
})

I have another collection "Regions" 我还有另一个收藏集“ Regions”

var regionsSchema = mongoose.Schema({
name: String,
athletes: [{ type: Schema.Types.ObjectId, ref: 'Athletes' }]
})

One athlete have a region but a region have multiple athletes. 一个运动员有一个区域,但是一个区域有多个运动员。 I don't understand how is that possible, when i create an athlete the model region knows if it's on this region or this region. 我不知道这怎么可能,当我创建运动员时,模型区域会知道它是在该区域还是该区域。

i had this to my server.js : 我有这个到我的server.js:

Athletes.find({name : datas.name}, function(err, name){
        if(name == ""){
            Athletes.create(datas, function(err, ath){
                   if(err || ath.name){
                       console.log(err)
                   }
                   Regions.create(regionName, function(err){
                    if(err){
                        console.log(err)
                    }
                })
           })

        }
    }) 

I check before create a new user if is not in the database, is not i create the athlete, but i don't know how to had his region in the Region model. 我在创建新用户之前检查是否不在数据库中,是否不是在创建运动员,但我不知道如何在Region模型中设置他的区域。

Maybe it would be easier for you to reverse this. 也许您更容易扭转这种情况。 Have regions only having the name. 具有仅具有名称的区域。 And then add regionId on the Athlete model: 然后在运动员模型上添加regionId:

region: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'Regions',
  index: true,
}

Then any time you update an Athlete, you're only updating this, athlete, object. 然后,无论何时更新运动员,您都只在更新运动员,对象。 Alternatively, dealing with arrays is not as simple. 另外,处理数组也不是那么简单。

With this you can query (and populate), eg all athletes from given regions: 您可以使用此查询(并填充),例如来自给定区域的所有运动员:

Athletes.find({ region: [region1, region2]})
  .populate('region')

Now, updating region name is simplified, you do it in one place, not on all athlete instances. 现在,简化了区域名称的更新,您可以在一个地方而不是在所有运动员实例上进行。

There are more complex scenarios where you want to be querying things by various criteria, but most of the times, this would be the simplest way. 在更复杂的场景中,您希望通过各种条件查询事物,但是在大多数情况下,这是最简单的方法。

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

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