mongoose 试图填充字段但没有发生

nlejzf6q  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(95)

我有两个模型的职位和用户,我想填充用户领域的职位,但由于某些原因,它不工作
后图式

import mongoose, { Schema, mongo } from "mongoose";

const postSchema = new Schema({
    description : {
        type : String,
        required : true,
        maxLength : [250 , "You can type upto only 250 characters"]
    },
    img : {type  : String},
    date : {
        type : Date,
        default : new Date(Date.now()),
        required : true
    },
    user : {
        type  : mongoose.Schema.Types.ObjectId,
        ref : 'User',
        required : true,
    },
    likeCount : {
        type : Number,
        required : true,
        default : 0

    }, 
    comments : {type : [{
        text : String,
        postedBy :{
            type : mongoose.Schema.Types.ObjectId,
            ref : "User"
        }  
    }],
    default : []
    }
})

export const Post = mongoose.model("post",postSchema)

字符串
用户模式

import mongoose, { Mongoose } from "mongoose";
import { Schema } from "mongoose";

const userSchema =  new Schema({
    name : {
        type : String,
        required : true,
        unique : true
    },
    password : {
        type : String,
        required : true,
    },
    email : {
        type : String,
        required : true,
        unique : true
    },
    followingList : [{type : mongoose.Schema.Types.ObjectId , ref : "User" , unique : true}],
    followerList : [{type : mongoose.Schema.Types.ObjectId , ref : "User", unique : true}],

    followRequests : {type : [{
        userId : {
            type : mongoose.Schema.Types.ObjectId,
            ref : "Users",
            required : true
        },
        isAccepted : {type : Boolean , default : false}
    }],
    default : []
    },
})

export const User = mongoose.model('User',userSchema)


取帖码

export const getAllUserPosts = async(req,res) => {
    const {id} = req.params
    const userPosts = await Post.find({user : id}).populate("user","name,_id")
    res.status(200).json(
        {
            userPosts
        }
    )
}


我试过了网上所有的东西,但没有什么实际上帮助我它没有抛出任何错误,它实际上执行,它应该在帖子中显示用户的名称和ID,但它只显示ID,我无法找出实际问题发生的地方,即使阅读文档,我也没有在我的代码中看到任何问题

ymzxtsji

ymzxtsji1#

您的填充格式不正确。.populate("user", "name,_id")无效。看起来你想做name._id?您只需要填充具有mongoose.Schema.Types.ObjectId类型的字段。编辑:看起来你用逗号代替了空格。这可能会解决它。
见下文:
控制器:

module.exports.createBook = async (req, res) => {
    try {
        const {_id, displayName} = jwt.verify(req.cookies.userToken, secret)
        const myBook = new Book(req.body)
        myBook.addedBy = _id
        myBook.addedByString = displayName
        myBook.favoritedBy.push(_id)
        let newBook = await myBook.save()
        await newBook.populate("addedBy favoritedBy")
        await User.findByIdAndUpdate(newBook.addedBy, {$push: {booksAdded: newBook._id, booksFavorited: newBook._id}})
        res.json({ book: newBook })
        // console.log("inside try")
    }catch(err){
        console.log(`inside catch`, err)
        res.status(400).json({ message: "Something went worng creating a book", error: err }) //error isnt specific to either try line
    }
}

字符串
产品型号:

const mongoose = require('mongoose')
const { findOneUser } = require('../controllers/user.controller')

const BookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, "Title is required"],
        minlength: [2, "Title must be at least 2 characters"]
    },
    author: {
        type: String,
        required: [true, "Author is required"],
        minlength: [2, "Author must be at least 2 characters"]
    },
    addedByString: {
        type: String
    },
    addedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        required: [true, "Added-By field is required"]
    },
    favoritedBy: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
},
    { timestamps: true }
)

module.exports = mongoose.model('Book', BookSchema)

相关问题