How to save a record associated with multiple user in Mongodb?

时间:2018-07-25 05:25:21

标签: node.js mongodb mongoose mongoose-schema

My Schemas are: Schema for User

const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
    name:String,
    mobile:String,
    meals:[{type:Schema.Types.ObjectId, ref: 'Meal'}],
    deposits:[{type:Schema.Types.ObjectId, ref: 'Deposit'}],
    costs:[{type:Schema.Types.ObjectId, ref: 'Cost'}]
},
{ 
    usePushEach: true 
});

var User = mongoose.model('User', userSchema);
module.exports = User;

Schema for Costs

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

var costSchema = new Schema({
    persons:[{type:Schema.Types.ObjectId, ref: 'User'}],
    amount:Number,
    date:{type:Date, default:Date.now},
    market:String,
    costType:String
},
{ 
   usePushEach: true 
});

var Cost = mongoose.model("Cost", costSchema);
module.exports = Cost;

The problem is, How to save the Costs

app.post('/cost', adminPass, (req, res)=>{
    User.find({}, (err, user)=>{
        let data= {
            date:req.body.date,
            amount:req.body.amount,
            market:req.body.market,
            costType:req.body.costType
         };
        let id1=req.body.id1, id2=req.body.id2;
        Cost.create(data, (err, cost)=>{
            if(err){console.log(err);}
            cost.persons.push(id1);
            cost.persons.push(id2);
            cost.save();
            user.costs.push(cost);
            user();
            console.log(cost);
            res.redirect('/cost');
        });
    });
});

Most of other things is working pretty fine but the problem with adding persons to each cost record and also pushing that record to the user record. for further details please comment. I am getting this error.

{ 
  _id: 5b58056c63eca912f43e370f,
  amount: 1000,
  market: 'অন্যান্য',
  costType: 'Grocery',
  __v: 0,
  date: 2018-07-27T00:00:00.000Z,
  persons: [] }
E:\File\Practice\node.js\scs\node_modules\mongodb\lib\utils.js:98
     process.nextTick(function() { throw err; });
                              ^

TypeError: Cannot read property 'push' of undefined

1 个答案:

答案 0 :(得分:0)

您的“成本模式”需要一个人的默认值,将其默认设置为[],这就是为什么您会得到未定义的错误的原因。