node.js - 如何获取引用文档在 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*/
是否可以像这样查询或者我需要更改人员架构
解决方案
如果您想通过 ObjectId 查找任何内容,则必须使用以下语法:
const persons = await Person.find({"stories.author":mongoose.Types.ObjectId(author_id)}).populate('stories');//<==== Replace author_id with your actual variable.
推荐阅读
- jenkins - 具有 SSH 代理的 Jenkins 中的权限从节点
- sql - 在 1 列 SQL Server 上选择具有重复值的行
- android - Facebook Android SDK:通过应用范围的 userId 获取用户
- php - 如何在 Laravel 中为 Pivot 模型用户路由模型绑定
- typescript - 将 Next.js 与 typescript 一起使用,但不能在 WithRouterProps 中应用泛型
- javascript - 在 reactJs 中使用 id 滚动到特定 div 而不使用任何其他库
- android - Java.Lang.NoSuchMethodError:没有非静态方法“Landroid/content/Context;.getColorStateList(I)Landroid/content/res/ColorStateList;”
- angular - Angular 6 - 使用await for http客户端,如果失败我如何获得状态码
- svg - SVG动画查询
- solr - 如何使用 TZ 参数在 solr 中获取文字日期范围查询