【问题标题】:Store Country, City and User info using mongoose and nodejs MongoDB使用 mongoose 和 nodejs MongoDB 存储国家、城市和用户信息
【发布时间】:2016-08-17 20:20:32
【问题描述】:

我想在我的新项目中使用 mongodb。那是第一次,我使用 mongodb。在关系数据库中,我保存的数据如下:

tbl_country > id,name,created_at,etc..
tbl_city    > id,country_id,name,created_at,etc...
tbl_user    > id,name_surname,city_id,etc...

在这个模式中,我可以通过使用外键找到一个城市的国家、用户的国家等等。

您建议通过带有 mongodb 的 nodejs 以最佳性能创建这样的模式?

【问题讨论】:

    标签: node.js mongodb mongoose schema relationship


    【解决方案1】:

    您仍然可以在创建架构时使用外键。请将此模式作为您给出的示例进行检查。

    var CountrySchema = new Schema({
      name: String,
      created_at: Date
    });
    
    var CitySchema = new Schema({
      countryName: { type: mongoose.Schema.Types.ObjectId, ref: 'Country' },
      created_at: Date
    });
    
    var UserSchema = new Schema({
      name_surname: String,
      city: { type: mongoose.Schema.Types.ObjectId, ref: 'City' }
    })
    
    mongoose.model('Country', CountrySchema);
    mongoose.model('City', CitySchema);
    mongoose.model('User', UserSchema);
    

    当您获取数据时,您必须使用“填充”方法。例如:

    City.find()
    populate('countryName', 'name') // It will bring only name field
    .exec(function(err, cities) {
    })
    

    顺便说一句。 _id 由 mongo 为每个数据自动创建。因此,您不需要将 id 字段添加到您的架构中。希望能帮助到你。祝你好运

    【讨论】:

    • 我读了一些他们说会降低性能的文章?是真的吗?
    • 这取决于如何使用它。如果您只是将国家名称存储在您的架构中并且您不使用您的国家架构,则不需要使用参考 ID。您可以简单地将子文档添加到您的架构中。像 new Schema({ country: { name: String, code: Number } }) 或只是 new Schema({country: String})。在这种情况下,没有必要使用“refId”。它会降低性能。此外,您可能已经阅读过一些旧贴的文件。由于mongo已经被广泛使用,它已经发展了很多。因此,您不必担心人们认为 mongo 的初始阶段的性能。
    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多