猫鼬 - 通过作者的ID查找模型



我正在尝试通过作者的ID找到给定作者创建的所有帖子,但我一直在获得一个空数组

以下是模型,获取请求

let campgroundSchema = new mongoose.Schema({
    name:String,
    image:String,
    location:String,
    lat:Number,
    lng:Number,
    price:String,
    description:String,
    createdAt: {type:Date, default:Date.now},
    author:{
        id:{
            type:mongoose.Schema.Types.ObjectId,
            ref:'User'
        },
        username:String,
    },
    comments:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Comment'
    }]
});
let Campground = mongoose.model('campground',campgroundSchema);```
const userSchema = new mongoose.Schema({
    username:String,
    password:String,
    firstName:String,
    lastName:String,
    email:String,
    profileImage:String,
    isAdmin:{type:Boolean, default:false},
    followers:[
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:'User'
        }
    ],
    notifications:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Notification'
    }]
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model('User', userSchema);

嗨,我是否通过作者的ID获得了给定作者的所有露营地的数组,该想法是渲染用户模型中存储的用户详细信息的用户配置文件以及用户创建的帖子数量。

简单搜索post Collection

Post.find({author.id: req.params.id},(err, posts) => 
    {
       ....
    }) 

如果我正确理解您,您正在尝试通过作者ID返回所有营地。如果是这样,您的查询正在寻找错误的ID。

User.findById(req.params.id)

将在Mongo自动生成的本机_id上匹配的用户集合中的文档。

如果您想在作者ID上找到匹配的露营地,则您的查询应该看起来像:

User.find({ author.id: req.params.id })

希望这会有所帮助!

我解决了它。

router.get('/users/:id',(req,res) => {
     User.findById(req.params.id).populate('posts').exec((err,foundUser)=>{
        if (err) {
            req.flash('error_msg',"Something went wrong");
            res.redirect('/');
        } else {
            Campground.find({'author.id':foundUser.id},(err,foundUser_campgrounds)=>{
                res.render('users/show', {userProfile:foundUser, userCampgrounds:foundUser_campgrounds});
            });
        }
    });
});
const User=require('./models/user');
const Campground = require('./models/campgrounds');
app.get('/profile/:id',(req,res) => {
    const user = User.findById(req.params.id);
    const camp= Campground.find({author:user._id});
    res.send(camp);
});

最新更新