0
votes

I am saving data for farm in User ,but i have tried many things to save data to farm field.I have created an api that signup a user and data is saved ,farm is one of its object,I want to add farm after signup to that specific user .Recently i have tried to update and my code converts the farm into null.A user can have many farm.

I am using mongoose and express and passport for authentication .I have changed farm to Object,ObjectID,Array but none helps,everytime farm is converted to null.Is my schema correct ?

Schema

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

//Device Schema
const Device = new Schema({

  modelNumber: {
    type: String,
    required: true
  },
  deviceType: {
    type: String,
    required: true
  },
  description:{
      type:String,
      required:false   
  },

  deviceLocation:[ 
    {
      latitude:Number,
      longitude:Number
    }
  ],

  AddedDate: {
    type: Date,
    default: Date.now
  },

});

// User Schema
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true
  },
  location:{
      type:String,
      required:true
  },
  createdDate: {
    type: Date,
    default: Date.now
  },

  farm:[
      {
        _id:mongoose.Schema.Types.ObjectId,
        description:String,
        farmAddDate:{type:Date,default:Date.now},
        device:[{Device}]
     }
 ]   

});


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

Add Farm API

//@route POST api/user/addFarm
//@desc POST Register Farm
//@access Public  
addFarm=function (req,res){
  User.findOneAndUpdate({ farm: req.body.farm }).then(farm => {
    if (farm) {
      return res.status(400).json({ farm: "Farm already exists" });
    } else {
      const newFarm =  Farm({
       _id:req.body._id,
       description:req.body.description,
       device:req.body.device
      });
      newFarm
      .save()
      .then(farm => res.json(farm))
      .catch(err => console.log(err));
    }
  });
}
  router.post('/addFarm',addFarm);

Register New User

router.post("/register", (req, res) => {
  // Form validation
  const { errors, isValid } = validateRegisterInput(req.body);
  // Check validation
  if (!isValid) {
    return res.status(400).json(errors);
  }

  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "Email already exists" });
    } else {
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        location:req.body.location,


      });

      // Hash password before saving in database
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});


Error:

(node:7064) UnhandledPromiseRejectionWarning: CastError: Cast to embedded failed for value "\'DGR\'" at path "farm" at new CastError (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\error\cast.js:29:11) at DocumentArray.cast (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\schema\documentarray.js:402:19) at DocumentArray.cast (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\schema\documentarray.js:336:17) at DocumentArray.SchemaType.applySetters (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\schematype.js:892:12) at DocumentArray.SchemaType._castForQuery (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\schematype.js:1304:15) at DocumentArray.SchemaType.castForQueryWrapper (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\schematype.js:1271:17) at castUpdateVal (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\helpers\query\castUpdate.js:434:19) at walkUpdatePath (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\helpers\query\castUpdate.js:261:22) at castUpdate (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\helpers\query\castUpdate.js:79:18) at model.Query._castUpdate (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\query.js:4319:10) at castDoc (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\query.js:4347:18) at model.Query.Query._findAndModify (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\query.js:3325:19) at model.Query. (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\query.js:2902:8) at model.Query._wrappedThunk [as _findOneAndUpdate] (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8) at process.nextTick (C:\Users\Pritam Kumar\Documents\Mern auth\mern-auth-Sagita\node_modules\kareem\index.js:369:33) at process._tickCallback (internal/process/next_tick.js:61:11) (node:7064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:7064) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:7064) DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-

O/P

id:5d034237a9a144428459a120
name:"Auditi"
email:"[email protected]"
password:"$2a$10$qHvr3VurbyvJyuqbV11NVeKLjn8jhTuP7piI5yMNBOLOQac98zcC2"
location:"XYZ"
createdDate:2019-06-14T06:44:07.035+00:00
farm:Array(data is saved)
__v:0
1

1 Answers

0
votes
First of all, in the schema correct this:

     farm:[
          {
            description:String,
            farmAddDate:{type:Date,default:Date.now},
            device:[{Device}]
          }
      ]  

Do not use _id in farm array, _id is auto-generated field, it gets created itself when new entry is added. Also, you can not compare the whole array in a record.

User.findOneAndUpdate({ farm: req.body.farm }) 

This is wrong approach, it will never return a matched record.