Home > Blockchain >  updating relative schema in mongodb using nodejs
updating relative schema in mongodb using nodejs

Time:09-22

I am trying to update my 2nd schema which having reference in first schema

projectSchema.js

var projectSchema = Schema({
    pname     : String,
    description     : String,
    assignee : { 
                  type: Schema.Types.ObjectId,
                  ref: 'Assignment'
                }
});
var Project = mongoose.model('project', projectSchema);

assigneeSchema.js

var assigneeSchema = Schema({
    assigneeName  : String,
    grade  : String,
    startDate : Date,
    endDate   : Date
});
var Assignee  = mongoose.model('Assignment', shopSchema);

so I am trying to update my schema like this

const update = async (req, res) => {
  const { id } = req.params;
  let update = {};
  let updateAssignee={};
  if (req.body.pname) update.pname = req.body.pname;
  if (req.body.description) update.description = req.body.description;
  if (req.body.assignee.assigneeName) updateAssignee.assignee.assigneeName = req.body.assignee.assigneeName;
  if (req.body.assignee.grade) updateAssignee.assignee.grade = req.body.assignee.grade;

   let newProject = new Project.updateOne(
     { projectId: id },
      {
        $set: update,
      },
      { runValidators: true }
     );

   let newAssignee = new Assignee.updateOne(
     { projectId: id },
      {
        $set: updateAssignee,
      },
      { runValidators: true }
     );
};

I am trying to update shop but its not working and where am i wrong i dont know

CodePudding user response:

const update = async (req, res) => {
  const { id } = req.params;
  let update = {};
  let updateAssignee={};
  if (req.body.pname) update.pname = req.body.pname;
  if (req.body.description) update.description = req.body.description;
  if (req.body.assignee.assigneeName) updateAssignee.assignee.assigneeName = req.body.assignee.assigneeName;
  if (req.body.assignee.grade) updateAssignee.assignee.grade = req.body.assignee.grade;

   let newProject = new Project.findOneAndupdate(
     { projectId: id },
      {
        $set: update,
      },
      { runValidators: true,returnOriginal: false }
     );

   let newAssignee = new Assignee.updateOne(
     { _id: newProject.assignee },
      {
        $set: updateAssignee,
      },
      { runValidators: true }
     );
};

/// use findOneAndUpdate it will return new object after that get assignee Id and put in query of assignee

  • Related