mongoose Moongose通过ObjectId找到空数组

lf3rwulv  于 2023-03-03  发布在  Go
关注(0)|答案(2)|浏览(123)

我试图找到所有符合特定用户ID的文章。
以下是方案:

const articleSchema = new DB.Schema({
  title: { type: String, required: true },
  body: { type: String, required: true },
  user: { type: DB.Schema.Types.ObjectId, ref: 'User' },
  likes: [String],
  shares: [String],
  comments: [
    {
      text: String,
      user: String,
    },
  ]
}, { timestamps: true });

这是不工作的控制器:

const handleGetAllByUser = async (req, res) => {
  const { userId } = req.params;
  try {
    let articles = await Article.find({ user: userId }).populate('user', 'name');
    return res.status(200).json({ articles });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ error: err });
  }
};

我也试过这样做:

Article.find({user: mongoose.Types.ObjectId(userId)};

我知道这个问题以前有人回答过,这并不复杂,我只是不知道出了什么问题。

cqoc49vn

cqoc49vn1#

从请求参数中获取用户ID,例如,它是ObjectId的字符串表示。您的模型将用户定义为ObjectId,例如,二进制。
您需要将字符串转换为ObjectId:

let articles = await Article.find({ user: mongoose.Types.ObjectId(userId) }).populate('user', 'name');`
uxh89sit

uxh89sit2#

问题是某些文章已与用户一起保存为字符串:

由于某种原因,建议的查询都不起作用。修复方法是将该数据类型更新为ObjecId,因此:

那么我们可以简单地写:

Article.find({ user: userId }).populate('user', 'name');

这一个很有效,甚至不需要手动转换为ObjectId,因为mongoose似乎已经在后台完成了这一操作。

相关问题