【问题标题】:Populate not working in Mongoose填充在猫鼬中不起作用
【发布时间】:2016-12-24 01:45:26
【问题描述】:

我在使用 Mongoose 中的填充功能时遇到了一些问题。问题是联系人没有被排序,所以我得到了所有的联系人,不管我使用的是哪个俱乐部。

models.js

// Contactperson Schema
var contactPersonSchema = new Schema({
    club: {
        type: Schema.ObjectId,
        ref: 'Club'
    },
    name: String,
    phoneNumber: String,
    email: String,
    position: String,
    comment: String
});


// Club Schema
var clubSchema = new Schema({
    name: String,
    postalPlace: String,
    comment: String,
    status: String
});

routes.js

router.use('/api/clubs', clubRoute);

clubroutes.js

router.route('/:club_id/contactpersons')
    .post(function (req, res) {
        var contactperson = new Contactperson();
        contactperson.club = req.body.club;
        contactperson.name = req.body.name;
        contactperson.phoneNumber = req.body.phoneNumber;
        contactperson.email = req.body.email;
        contactperson.position = req.body.position;
        contactperson.comment = req.body.comment;

        contactperson.save(function (err) {
            if (err) {
                res.send(err);
            }

            res.json({message: 'Contactperson created!'});
        });
    })
    .get(function (req, res) {
        console.log(req);
        Contactperson.find({}).populate('club').exec(function (err, contactpersons) {

                if (err) {
                    res.send(err);
                }

                res.json(contactpersons);
            });

    });
Angular 中的

clubDetail.js(我正在使用 Restangular)

$scope.club = clubService.one($routeParams.id).get().$object;

$scope.contactpersons = clubService.one($routeParams.id).all('contactpersons').getList().$object;

【问题讨论】:

  • 检查您的 ref 集合名称是否在您的数据库中恰好是“俱乐部”
  • module.exports = mongoose.model('Club', clubSchema);我尝试将其更改为“clubs”和“club”,但随后出现错误:MissingSchemaError: Schema has not been registered for model "club"
  • 结果如何?
  • 我不太清楚你的意思,但如果你指的是对象的外观,我在这里截取了控制台的屏幕截图:s3.postimg.io/bbsrk8br7/stackoverflow.png

标签: angularjs node.js mongodb mongoose restangular


【解决方案1】:

我终于找到了答案。问题是我没有定义俱乐部。以下是正确的查找方法:

Contactperson.find({club:req.params.club_id}).populate('club').exec(function (err, contactpersons) {

【讨论】:

  • 很高兴你让它工作了,但这种变化与让人口工作有什么关系?那不只是将返回的文档过滤为匹配club的文档吗?
  • 是的,这就是我想要完成的。这不就是您要使用填充的目的吗?
  • 否,population 用于跟进您的原始 Contactperson 查询,并使用第二个到引用的(俱乐部)模型来拉入引用的俱乐部文档,替换 club ObjectId文档的联系人。
猜你喜欢
  • 2018-06-10
  • 2014-12-19
  • 2013-06-20
  • 1970-01-01
  • 2017-01-10
  • 2014-05-01
  • 2021-02-03
  • 1970-01-01
  • 2015-09-17
相关资源
最近更新 更多