首页 > 解决方案 > 填充不工作,不填充代码工作

问题描述

我在填充模式的字段时遇到问题,我尝试了很多次,但我无法弄清楚问题:FUNCTION:

 function xyz (req, res) {
    User.findOne({_id: req.payload._id })
        .populate("ABC.xyzID")
        .exec((err, user) => {
        if (err) {
            return res.json ({'success': false, 'message': 'Could not retrieve ABC.'});
        }
        console.log(user);
        return res.json ({'success': true, 'message': 'ABC fetched successfully', user });
    });

}

架构:

const UserSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true,
        trim: true
    },
ABC:{
        xyzID:{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'xyz'
        },
},
LMN:{
          yyyID:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'yyy'      
        }], 
         EmployeeID:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'            
        }]
    }

});

在这里我可以通过填充它来访问:LMN.yyyID,但它不适用于 ABC.xyzID,没有填充我可以看到 xyzID,但它的 _id 格式。所以基本上它只是填充不起作用

标签: mongoosepopulate

解决方案


请看这个 Schema 设计。这是用户。

// user.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create schema
const UserSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});

module.exports = User = mongoose.model('user', UserSchema);

现在这里是活动模式。现在你可以看到我从“用户”架构中引用 userId。因此,您需要确保您的集合名称和参考名称相同。在此之后,它应该工作。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create schema
const ActivitySchema = new Schema({

    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    text: {
        type: String,
        required: true
    }
});

module.exports = Activity = mongoose.model('activity', ActivitySchema);

然后尝试查询

Activity.findOne({_id: req.payload._id })
     .populate('userId')
     .then(result => { console.log(result); })
     .catch(err => { console.log(err); });

您将在 userId 对象中看到用户信息。


推荐阅读