node.js - 在猫鼬中填充返回空数组,我被卡住了
问题描述
我正在通过 MERN 堆栈为 goodreads 创建模拟,当我使用填充来检索特定用户的书籍时,它返回空数组,我做了很多搜索,但这是我的模型
const userSchema =new mongoose.Schema({
firstName:{
type:"string",required:true
},
books:[{
book:{type:mongoose.Schema.Types.ObjectId,ref:'Book'},rate:Number,shelve:''
}]});
这是书籍模型
const bookSchema =new mongoose.Schema({
title :{
type:"string",required:true
}});
这就是我使用填充的方式
router.get("/one", (req, res, next) => {
User.find({firstName : "John"}).populate("books").exec(function (err, user) {
res.json(user)
});
})
这是生成的 json
[{"_id":"5c70f299ef088c13a3ff3a2c","books":[]}]
解决方案
您正在引用book
书籍数组中的对象,因此您需要填充books.book
.
User.find({firstName : "John"}).populate("books.book").exec(function (err, user) {
res.json(user)
});
推荐阅读
- javascript - 冻结网页的父窗口的问题(打开的窗口不会在 Chrome 中加载)
- sql-server - SQL 案例评估失败?
- r - 这个 Pmin() 函数如何对列进行索引?
- git - pyCharm 会在 git commit 之前自动添加吗?
- sql - 从 Oracle 视图访问 URL
- elasticsearch - 来自 Kibana 发现选项卡的正则表达式查询对来自 logstash 的日志
- flutter - 未定义的名称“文本”
- javascript - 捕获错误:具有名称的无效表单控件不可聚焦
- pytest - 如何在pytest的模型中为自引用列创建工厂列?
- html - HTML CSS div 标签属性混淆