gpt4 book ai didi

node.js - Mongoose - 通过 Id 找到 child

转载 作者:可可西里 更新时间:2023-11-01 10:45:24 24 4
gpt4 key购买 nike

详细信息:这是我的模式布局

Schema Layout:
const mongoose = require("mongoose");

module.exports = function(db) {

let gameSchema = new mongoose.Schema({

opponent: String,
location: String,
date: String,
completions: Number,
attempts: Number,
yards: Number,
touchdowns: Number,
interceptions: Number,
});

let quarterbackSchema = new mongoose.Schema({
firstName: String,
lastName: String,
school: String,
age: Number,
hometown: String,
games:[gameSchema]
});

这是存储文档的样子

{
"_id": {
"$oid": "5c0a551df8555c1c1ef0c101"
},
"firstName": "Pepper",
"lastName": "Princess ",
"age": 14,
"hometown": "Farmville, Ms",
"school": "Farmers School of Important Stuff",
"games": [
{
"_id": {
"$oid": "5c0ca5ba7213fe6a5f52848c"
},
"opponent": "Crock McSnagglebite",
"location": "Pattys Putrid Flower Garden",
"date": "1/23/2020",
"completions": 777,
"attempts": 777,
"yards": 777,
"touchdowns": 777,
"interceptions": 777
}
],
"__v": 1
}

问题:我正在尝试通过其 _id 查找子文档。我发布的示例代码将数字显示为“5c0ca5ba7213fe6a5f52848c”。

我试过了

 Quarterback.find({_id: req.body.id}).then(function(Results){});

Quarterback.findOne({_id: req.body.id}).then(ect...

Quarterback.findById({_id: req.body.id}).then(ect...

还有很多很多其他方式,我根本不知道我做错了什么。我用过

JSON.stringify(req.body));验证路由是否返回了我想要的值,它是
我的 console.log 输出以下内容

这是游戏详情 req.body::{"child":"5c0d02649c936072d47f12a9"}

但在使用上述方法时,find 始终返回 null 作为结果。我是一名学生并且还在学习,所以也许我错过了一些简单的东西。我希望这里有人可以提供帮助。非常感谢您的宝贵时间!!

最佳答案

您的四分卫架构有误。games:[gameSchema] 应该是

games:[game:{type: Schema.Types.ObjectId,ref: 'games'}]更正此问题后,您应该能够运行此查询:Quarterback.find({games: req.body.id}).then(function(Results){});

关于node.js - Mongoose - 通过 Id 找到 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53699000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com