search

Home  >  Q&A  >  body text

javascript - How to use mongoose joint query populate?

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?

迷茫迷茫2714 days ago649

reply all(1)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:52:40

    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

    reply
    0
  • Cancelreply