Home > Net >  Why .save( ) is not and throwing error as ``TypeError: sourceData.save is not a function``?
Why .save( ) is not and throwing error as ``TypeError: sourceData.save is not a function``?

Time:02-28

Here is the code of my source model:

const sourceSchema = new Schema(
    {
        name:{
            type: String,
            required: true
        },
        url:{
            type: String,
            required: true
        },
        data:{
            posts:[
                {
                    postId: {
                        type: Schema.Types.ObjectId,
                        ref: 'Post',
                        required: true
                    }
                }
            ]
            
        },
        oldState:{
            type: Array,
        },
        currentState:{
            type: Array
        }

    }
);


I have a source saved in the database and now I want to update the currentState value and save it. articles is an array of objects [{....},{.....},{.....}]

Here is my updation code:

Source.find({name: 'National News'})
              .then(sourceData=>{
                  console.log(sourceData);
                  sourceData.currentState= articles;
                  return sourceData.save();
              })
              .then(result=>{
                  console.log(result);
                  next();
              })
              .catch(err=>{
                  console.log(err);
              })

I am able to see in the console that the correct source has been selected as console.log(sourceData) gives the right data but after that, I get the error as TypeError: sourceData.save is not a function

I also tried using sourceData.markModified('currentState') before sourceData.save() but then it started to give TypeError: sourceData.markModified is not a function.

I even tried sourceData.update() but that also did not work.

I am new to node.js and the tutorial which I followed only used .save() to update data and I was working there. Please help me to resolve this problem.

CodePudding user response:

The .find method returns an array as the result. You might want to use .findOne instead.

  • Related