首页 > 解决方案 > 如何获取引用文档在 mongoosejs 中有一些字段的文档

问题描述

首先,我对 MongoD 完全陌生,我尝试了很多搜索,但没有找到任何解决方案,或者我搜索错误。假设我有以下文件

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

我可以用他们的故事来询问这样的人

const persons = await Person.find().populate('stories');

我需要查询有特定作者故事的人

const persons = await Person.find({"stories.author":"someobjectid"}).populate('stories');

// This didn't work*/

是否可以像这样查询或者我需要更改人员架构

标签: node.jsmongodbmongoose

解决方案


如果您想通过 ObjectId 查找任何内容,则必须使用以下语法:

const persons = await Person.find({"stories.author":mongoose.Types.ObjectId(author_id)}).populate('stories');//<==== Replace author_id with your actual variable.

推荐阅读