簡體   English   中英

Mongoose 填充

[英]Mongoose populating

我是 mongoose 和 mongodb 的新手,並且一直試圖將我的用戶與一堆圖片帖子聯系起來。 我讀了很多關於 mongoose 填充但我不斷得到空圖像 []。

 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 但仍然得到相同的結果 - 一個空數組

在我看來,您應該丟棄不能作為用戶 model 鏈接的 id 部分。 換句話說,嘗試類似:

const imageSchema = new mongoose.Schema({
image: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
})

我認為這應該填充正確的數組。

此外,當您獲得值時,您將獲得一個對象數組。 所以你需要 map 在它上面。 lastTenImages.images不會產生任何東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM