javascript - How to use mongoose joint query populate?
迷茫
迷茫 2017-06-26 10:50:40
0
1
663

When using node to practice blogging projects, articles need to be associated with users, categories, and comment collections, so I used mongoose’s populate query, but it could not return the desired data. The code is as follows:

Save the article:

    // 拿到session中的用户信息
    let authorObj = {author: ObjectId(req.session.userInfo.userID)};
    let cateObj = {category: ObjectId(req.body.category)};
    // 增加到数据中
    postData = Object.assign(req.body,authorObj,cateObj);
    // 添加新数据
    postModel.create(postData)
        .then((result)=>{
            if(!result){
                reMessage.msg='文章保存错误';
                reMessage.code=2003;
                res.send(reMessage);
                return;
            }
            reMessage.msg='文章发表成功';
            reMessage.code=0;
            res.send(reMessage);
        });

Return data:

postModel.find({})
        .populate({path:'users',select:'username'})
        .then((data)=>{
            console.log(data);
            res.render('admin/posts-list',{
                login:req.session.login,
                userInfo:req.session.userInfo,
                fields:['标题','作者','分类','发表时间'],
                datas:data
            });
        });
        
        
        

The specific code is as above, why doesn’t it work?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
曾经蜡笔没有小新

Solved, it is the field ref reference error when creating Schema. The first parameter of userModel = db.model('user',suerSchema) should be referenced instead of userModel

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template