javascript - 猫鼬居住
问题描述
我是 mongoose 和 mongodb 的新手,我一直在尝试将我的用户与一堆图片帖子联系起来。我读了很多关于 mongoose populate 的文章,但我不断收到空图像 []。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
images: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Image'
}
]
});
module.exports = mongoose.model('User', userSchema);
const mongoose = require('mongoose');
const imageSchema = new mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
image: {
type: String,
required: true
},
description: {
type: String,
required: true
},
})
module.exports = mongoose.model('Image', imageSchema);
const getOne = async (userId) => {
let lastTenImages = await User.findById(userId).populate('images').lean();
console.log(lastTenImages.images);
// return lastTenImages
}
我还使用了 mongoose.Types.ObjectId 而不是 Schema 但仍然得到相同的结果 - 一个空数组
解决方案
在我看来,您应该丢弃不能作为用户模型链接的 id 部分。换句话说,尝试类似:
const imageSchema = new mongoose.Schema({
image: {
type: String,
required: true
},
description: {
type: String,
required: true
},
})
我认为这应该填充正确的数组。
此外,当您获得值时,您将获得一个对象数组。所以你需要映射它。lastTenImages.images
不会产生任何东西。
推荐阅读
- google-analytics - 为电子商务项目的动态 URL 设置目标
- python - 在 scikit learn 中预测多个值作为模型结果
- android - 当我想从 Firebase 获取数据时,为什么应用程序会关闭?
- tcp - 进程和 TCPSocket 在水晶中没有正确关闭
- pandas - 如何将ndarray转换为pandas DataFrame
- r - 使用 ibmdbR 包在 R 对象中追加和更新 DB2 表行
- sql-server - SQL Express - 我可以对现有表进行分区以解决 10GB 文件大小限制吗?
- wpf - 将对象绑定到组合框和文本框
- c - memcpy:GCC 或实现优化?
- javascript - 使用 JavaScript 创建文件并在单击按钮时下载