【问题标题】:Why is MongoDB unable to populate() on this query?为什么 MongoDB 无法在此查询上填充()?
【发布时间】:2021-09-18 20:56:40
【问题描述】:

我有两个集合,定义如下:

user.model.ts

import { Schema, model, Model } from 'mongoose';
import { User } from './interfaces';

// Create model
const UserSchema = new Schema<User>({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  passDigest: { type: String, required: true },
  verified: { type: Boolean, required: true },
  codes: { type: [Schema.Types.ObjectId], ref: 'GameCode' },
  orders: { type: [Schema.Types.ObjectId], ref: 'Order' } // This will just be an array of IDs.
});

// Compile and export
export const UserModel: Model<User> = model<User>('User', UserSchema);

confirmation.model.ts

import { Schema, model, Model } from 'mongoose';
import { Confirmation } from './interfaces';

const ConfSchema = new Schema<Confirmation>({
  confNumber: { type: String, required: true, unique: true },
  user: { type: Schema.Types.ObjectId, ref: 'User' },
  verified: { type: Boolean, required: true }
})

export const ConfModel: Model<Confirmation> = model<Confirmation>('Confirmation', ConfSchema);

鉴于此设置,我应该(理论上)能够从 Confirmation 集合中获取文档,并根据我已阅读的所有文档使用该引用填充关联的用户。

但是,当我从 Confirmation 集合中获取文档并尝试填充(在 Express 路由处理程序函数中)时,情况并非如此:

// POST /users/confirm
//
// { confId: String, login: String, password: String }
export const confirmUser: RequestHandler = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const currentConf = await ConfModel.findById(req.body.confId).populate('User');
    res.send(currentConf);
  } catch (err) {
    res.status(500).send(`Unable to complete user confirmation request: ${err}`);
  }
}

我能够获取文档,但不会发生填充,user 属性永远不会被关联的用户文档替换。

确认文件(存储在 MongoDB Atlas 中):

用户文档(也存储在 Atlas 中):

我很困惑,因为根据文档,这应该可以工作。据我所知,除了:

  1. 定义两种模式/模型
  2. 在将接收填充的架构中定义一个引用,确保与您要填充的模型的名称相匹配
  3. 执行查询(在我的例子中,ConfModel.findById 按 _id 获取单个记录)
  4. 对该查询执行.populate(),并传递您之前使用的相同名称。

这与使用 async/await 有什么关系吗?我需要使用.exec() 吗?我也尝试过使用ConfModel.findById(...).populate('User').exec(...) 无济于事。

提前感谢您的任何建议,我真的迷路了,它必须是我忽略的非常简单的事情。

【问题讨论】:

  • 填充('user')不填充('User')

标签: node.js typescript mongodb express mongoose


【解决方案1】:

您必须填充confirmation.model 的字段,即user 而不是User

所以使用.populate('user') 而不是populate('User')

【讨论】:

  • 再次感谢,修复后完美运行。我显然误读了文档。
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 2013-11-03
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 2011-01-17
相关资源
最近更新 更多