猫鼬-通过ID查找孩子

时间:2018-12-10 03:11:05

标签: node.js mongodb mongoose handlebars.js

详细信息:这是我的架构布局

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输出以下内容

这是游戏的详细信息。正文:{“ child”:“ 5c0d02649c936072d47f12a9”}

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

3 个答案:

答案 0 :(得分:0)

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

应该工作。您必须传递game._id,因为这就是访问JSON对象和属性的方式

答案 1 :(得分:0)

您的四分卫模式存在错误。 games:[gameSchema]应该是

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

答案 2 :(得分:0)

你可以试试

const quarterback =  Quarterback.find({_id: req.body.quaterbackId})
const game = quarterback.games.id(req.body.gameId)