问题描述
我正在使用 Express 和 Mongoose 来执行一些数据库操作。当尝试填充键包含空格的路径时,它基本上会被忽略。
MongoDB 模型:
document.querySelector(".tabInfo").innerHTML = tabInfo;
查找 + 填充:
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,});
我假设路径没有被填充,因为键中有空格。我尝试过点符号和输入 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 }
,但都没有运气。
有没有什么方法可以解决这个问题而不必重写架构结构?
解决方法
正如 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')