如何将父模式的ObjectId与同一事务中的子模式相关联?

时间:2017-08-16 10:48:24

标签: node.js mongodb mongoose ejs mongoose-schema

我有两种类型的实体usersfamilies,家庭和用户之间存在多对一关系,因此一个家庭可以拥有多个用户,但一个用户只有一个家庭。我试图创建一个试图实现这种关系的Mongo模式,但不确定这是否是正确的方法。

我的HTML页面上有一个按钮,单击该按钮将生成一个家庭代码,并为该族实体创建一个新的族属性。但是,我无法将新生成的family.ObjectId与用户实体中用户的familyid属性相关联。

知道我做错了吗?

我的模特:

家庭模式:

var mongoose = require("mongoose");
var shortid = require('shortid');
//Set Schema
var familySchema = mongoose.Schema({
    individuals: [{
           type: mongoose.Schema.Types.ObjectId,
           ref: "User"
        }],
    familyCode: {
            type: String,
            'default': shortid.generate
    }
});

//setup and export the model
module.exports = mongoose.model("Family", familySchema);

用户型号:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username:   String,
    password:   String,
    image:      String,
    firstName:  String,
    lastName:   String,
    accountid:  String,
    isAdmin:    {type: Boolean, default: false},
    userlabel: String,
    familyid:
        { type : mongoose.Schema.Types.ObjectId,
            ref: "Family"}
         });

UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

我的路线:

router.post("/familySetup", function(req, res){
    if(!req.body.familyid){
        var familyCode = shortid.generate();
        console.log(familyCode);
        // var individuals = {id:req.user._id}
        var newFamily = {familyCode:familyCode};

        Family.create(newFamily, function(err, newFamily){
            if(err){
                req.flash("error", "something seems to have gone amiss. Please try again.")
                console.log(err);
                res.redirect("home")
            }else{
                var updatedUser = {familyid:newFamily._id}
                console.log(updatedUser);
                User.findByIdAndUpdate(req.params.user_id, updatedUser, function(req, res){
                    if(err){
                        console.log(err);
                    }else{
                          //redirect to index
                        res.redirect("/familySetup");                    
                    }
                });
            }
        });
    }else{
        alert("You already have a family account");
        res.redirect("back");
    }
});

根据我得到的错误,我可以创建familyCode并能够创建变量updatedUser。但它不会使用新属性更新用户。运行代码时出现错误:

ByJyRqb_Z
{ familyid: 59941dd6589f9a1c14a36550 }
events.js:141
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'redirect' of null
    at /home/ubuntu/workspace/mbswalay/routes/family.js:44:28
    at Query.<anonymous> (/home/ubuntu/workspace/mbswalay/node_modules/mongoose/lib/model.js:3755:16)
    at /home/ubuntu/workspace/mbswalay/node_modules/mongoose/node_modules/kareem/index.js:277:21
    at /home/ubuntu/workspace/mbswalay/node_modules/mongoose/node_modules/kareem/index.js:131:16
    at nextTickCallbackWith0Args (node.js:436:9)
    at process._tickCallback (node.js:365:13)

2 个答案:

答案 0 :(得分:0)

它似乎不是mongodb的错误,它与路由配置有关,似乎使响应对象为空

答案 1 :(得分:0)

User.updateOne(
    { _id: req.params.user_id },
    { $set: { familyid: newFamily._id } }
  )

您必须使用 $set 运算符设置属性的值。