【问题标题】:Populate Data In mongoose not working properly?在猫鼬中填充数据无法正常工作?
【发布时间】:2017-09-22 14:27:38
【问题描述】:

我有两个集合useruserMapping 用户对象与其他信息一起映射到用户映射集合中。我在其中使用了引用。

这是我创建的架构:

    var userSchema = new userSchema({
    userId : {type : mongoose.Schema.Types.ObjectId, ref : 'UserMapping'},
    firstName: { type: String, required: true},
    middleName : String,
    lastName: { type: String, required: true},
    jobTitle : String,
    signumId : { type: String, required: true},
    //userGroupId : { type: String, required: true},
    emailAddress : { type: String, required: true, unique: true},
    contactNumber : String,
    status : Boolean,
    image : String,
    createdDate : String,
    lastUpdatedData :  String,
    lastLogin: String
});
    var userModel = mongoose.model('User', userSchema);

而 UserMapping 架构是:

var userMappingSchema = new userMappingSchema({
    userId: String,
    userGroupId : { type: String, required: true},
    createdDate : String,
    lastUpdatedData :  String
});

var userMappingModel = mongoose.model('UserMapping', userMappingSchema);

然后我尝试填充数据,我只从用户集合中获取数据,而不是从用户映射集合中获取数据。

数据库保存代码:

   var userMappingWithGroup = new userMapping({
                        "userId": newUser._id,
                        "userGroupId": req.body.userGroupId
                    });

                    userMappingWithGroup.save(function(err, userGroup) {
                        if (err) {
                            res.json({
                                "message": err.message,
                                "statusCode": err.code
                            });
                        } else {
                            newUser.userId = userGroup._id
                            newUser.save(function(err) {
                                if(err){
                                    res.json({
                                        "message": err.message,
                                        "statusCode": err.code
                                    });
                                }else{
                                    customError.errCode = 113;
                                    next(customError);
                                }
                            });
                        }
                    });

这里是填充代码:

   var User = require('../models/user').userModel;
    var userMapping = require('../models/userMapping').userMappingModel;

    var fetchEditUser = function(req, res) {
        console.log(req.params._id);
        User.findOne({userId: req.params._id})
            .populate('userId')
            .exec(function (err, result) {
            if(err) {
                res.json({"message":"Error On Fetching Users from DB", "errorCode":500 });
            }
            else {
                console.log(result);
                res.json({"message":"success", "errorCode":200, "data": result });
            }
        });
};

谁能帮助我哪里做错了,我是 mongoDB 的新手。

【问题讨论】:

  • 您正在填充用户模型,而引用存储在 userMapping 中。再检查一遍。
  • 我想在获取表单用户集合的同时获取数据。请告诉我该怎么做。
  • 为此您需要在用户架构中添加一个字段为userId: {type : mongoose.Schema.Types.ObjectId, ref : 'UserMapping'}
  • 我也是这样做的,但是只从用户集合而不是从用户映射中获取数据......我将更新我的代码
  • 好的,更新代码如何在 user 和 userMapping 中插入数据。

标签: node.js mongodb


【解决方案1】:

我不完全确定您要在这里实现什么,但您的 Schema 和 Call 看起来有问题。

您正在 UserMapping 架构中添加引用。如果你想使用它,你需要

UserMapping.find({}).populate('userId')

这样UserMapping.find({}) 将获得所有映射,populate('userId') 将用User 的对象替换userId 值。

更新:
如果你想从Users获取数据然后填充映射,你需要在@中添加userMappingId的引用987654330@ 架构。

另外,我认为userIdtype 应该是mongoose.Schema.ObjectId

示例
如果要获取文章及其作者的列表,则必须在 Article 架构中添加 userId 引用。

Article.find().populate("userId")

看看这个: http://mongoosejs.com/docs/populate.html

【讨论】:

  • Usermapping 集合结构是 userId 和 groupId,在这种情况下,我在用户架构中也有参考 UsermappingId。
  • 嗨安妮塔。您不需要双方的参考。我已经向你展示了两个选项。如果您在User 中提供UserMapping 的引用,那么您可以使用User 架构并填充UsermappingId。但是您在UserMapping 中给出了userId 的参考。这样,您将不得不UserMapping.find
  • 您必须使用添加引用的架构来获取记录。
【解决方案2】:

更新将数据保存到用户和用户映射的代码。在保存用户的最后一个 else 中,有两个部分,您可以根据需要申请。

var userMappingWithGroup = new userMapping({
        "userId": "",
        "userGroupId": req.body.userGroupId
    });

    userMappingWithGroup.save(function(err, doc) {
        if (err) {
            res.json({
                "message": err.message,
                "statusCode": err.code
            });
        } else {
            // customError.errCode = 113;
            // next(customError);
            var newUser = new user(req.body);
            newUser.userId = doc._id
            newUser.save(function(err, user){
                if(err){
                    res.json({
                        "message": err.message,
                        "statusCode": err.code
                    });
                }else{

                     //////////// this  //////////////////////  
                     customError.errCode = 113;
                     next(customError);

                     ///////////// OR  ///////////////////////

                     // userMappingWithGroup.userId = user._id;
                     // userMappingWithGroup.save(function(err, res){
                     //     if (err) {
                     //         res.json({
                     //             "message": err.message,
                     //             "statusCode": err.code
                     //         });
                     //     } else {
                     //         customError.errCode = 113;
                     //         next(customError);
                     //     }
                     // })
                }
            })
        }
    });

【讨论】:

  • 一个问题是 objectId 被保存以用于参考目的。或者我们必须使用的其他一些唯一的唯一字段。
  • 感谢您的回答,对我很有帮助
  • Mongoose 仅​​支持 _id 用于人口。没有其他字段,但它可能是唯一的,但不计入人口。
  • 如果这解决了您的问题,请评论您的查询是否正常。
  • 它对我来说工作正常,但必须传递 userGroupId 而不是 userId。我不想要。我想用 UserId 获取数据。我认为为此我必须根据我的理解将 userId 映射到 userGroup 集合中。如果我错了,请纠正我。
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2019-07-07
  • 2017-01-07
  • 2013-03-31
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多