【问题标题】:populate in nodejs and mongoose not worked填充nodejs和猫鼬不起作用
【发布时间】:2021-02-03 11:46:23
【问题描述】:

我有一个用于保存信息的架构,在这个信息中我有一个userId,我想返回该架构的信息并返回用户表单user 架构的信息。

TravelRequestSchema:

 const TravelRequestSchema = new Schema({
    userId: { type: Schema.Types.ObjectId, ref: "User" }
    description: { type: String, require: true }
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

用户架构:

 const UserSchema = new Schema({
    firstName: { type: String },
    lastName: { type: String },
    phoneNumber: { type: String },
    email: { type: String, defult: null }
},{
        toJSON: { virtuals: true }
});

现在我写这个问题是为了获取信息:

await TravelRequestModel.find({})
        .populate('User')
        .exec();

但它不会为我返回用户信息,它只是返回UserId

现在我该如何解决这个问题??

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    您希望查询填充特定字段,而不是模型名称

    await TravelRequestModel.find({})
            .populate('userId')
            .exec();
    

    这是因为如果您有多个引用同一模型的字段,您希望能够挑选并选择要填充的字段

    【讨论】:

      猜你喜欢
      • 2014-12-19
      • 2013-06-20
      • 1970-01-01
      • 2016-12-24
      • 2014-05-01
      • 2018-06-10
      • 1970-01-01
      • 2020-08-27
      • 2015-07-13
      相关资源
      最近更新 更多