详细信息:这是我的架构布局
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));验证路线是否返回了我想要的值,它是
my console.log outputs the following
这是游戏细节req.body :: {“child”:“5c0d02649c936072d47f12a9”}
但是当使用上述方法时,find会继续为结果返回null . 我是一名学生,仍然在学习,所以也许我错过了一些简单的事情 . 我希望有人可以提供帮助 . 非常感谢您的参与!!
2 回答
您可以使用
mongoose populate
查找并显示id的子文档 . mongoose populate的链接:https://mongoosejs.com/docs/populate.html应该管用 . 您必须传递game._id,因为这是访问JSON对象和属性的方式