【问题标题】:Acess User Information from Appointment Schema从约会模式访问用户信息
【发布时间】:2016-11-23 16:48:31
【问题描述】:

我是 ExpressJs 和 NodeJS 的新手。我正在尝试将我的 userInformation 获取到 Appointment 架构。如何从约会模式访问我的用户模式?我很确定我们将不得不使用填充,但我不知道如何使用它

约会架构

var appointmentSchema = mongoose.Schema({
    userId: String,
    visitType : String,
    timeDuration : String,
    startTime : Date,
    endTime : Date,
    status : String

  });

用户架构:

var userSchema = mongoose.Schema({
  _id : String,
  prefix : String,
  firstName : String,
  middleName : String,
  lastName : String,
  dob : String,
  age : Number,
  gender : String
});

提前致谢

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    好吧,我假设上述 两个 架构的名称分别是 AppointmentUser,到目前为止,这些架构之间没有任何关系,所以: p>

    第一件事:您需要提到Appointment 架构中的userId 属性引用User 架构如下:

    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    

    代替:

    userId: String,
    

    第二件事:在尝试从Appointment schema 获取您的用户信息时,您的查询将是:

    Appointment
      .find({ /* whatever your filters options */ })
      .populate('userId')
      .exec()
    

    了解更多关于猫鼬种群http://mongoosejs.com/docs/populate.html

    【讨论】:

    • 我们不应该在用户模式中添加 _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Appoinment' }。 @Basim Hennawi
    • UserAppointment是什么关系? 1:1? 1:N?另外,用户模式中的_id 属性指的是什么?用户 ID 还是约会 ID?
    • 1 : N,来自User的_id是约会Schema中的userId。
    • 你根本不需要明确地写这个_id属性,因为猫鼬默认为你的模式做这个。阅读更多:mongoosejs.com/docs/guide.html
    • 但是如果现有的 userId 可用,这将给出验证错误。我对吗?为了确认我正在处理的过程很好@Basim Hennawi
    猜你喜欢
    • 2019-04-18
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多