【问题标题】:Moongose: .populate on key with white space doesn't workMongoose:.populate on key with white space 不起作用
【发布时间】:2021-04-15 21:57:04
【问题描述】:

我正在使用 Express 和 Mongoose 执行一些数据库操作。当尝试填充键包含空格的路径时,它基本上会被忽略。

MongoDB 模型:

const OrgCrimeSchema = new Schema({
  gracePeriod: { type: Date, default: Date.now() },
  Technical: {
    description: String,
    difficulty: Number,
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  'Social Engineering': { // This one causes issues
    description: String,
    difficulty: Number,
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
  },
});

查找 + 填充:

const now = Date.now();
const allOrgCrimes = await OrgCrime.find({ gracePeriod: { $lte: now } })
    .populate('Technical.owner', 'name')
    .populate('Social Engineering.owner', 'name');

console.log(allOrgCrimes['Social Engineering'][0].owner); 
//5fca3b4a86e77b5c8e58b683

console.log(allOrgCrimes['Technical'][0].owner); 
// { name: 'npc_alice', _id: 5fae6d7ee60018434108369c }

我假设路径没有被填充,因为键中有一个空格。我尝试了点符号和输入{path: 'Social Engineering', select: 'name -id'},但没有运气。

有什么办法可以不用重写架构结构吗?

【问题讨论】:

    标签: mongodb express mongoose schema populate


    【解决方案1】:

    简而言之,没有办法,如果我们想同时填充多条路径,有这种办法

    例如

    Story
    .find(...)
    .populate('book author') // space delimited path names
    .exec()
    

    您可以看到以空格分隔的路径名。

    当你传递一个带空格的键时,猫鼬认为它是填充多个

    【讨论】:

      【解决方案2】:

      正如 Mohammad Yaser Ahmadi 指出的那样,今天没有解决此问题的方法,因为 populate 假设您正在填充多个而不是尝试读取中间有空格的路径名。我如何“解决”这个问题是将模型重写为:

      const OrgCrimeSchema = new Schema({
        gracePeriod: { type: Date, default: Date.now() },
        roles: [{
          role: String,
          description: String,
          difficulty: Number,
          owner: { type: Schema.Types.ObjectId, ref: 'User' },
        }]
      })
      

      然后填充实际上变得更容易:

      .populate('roles.owner', 'name')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-06
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 2023-03-30
        • 1970-01-01
        相关资源
        最近更新 更多