0

I'm a beginner in NodeJS and mongodB and I'm using mongoose and trying to update data of product using this code

  return new Promise((resolve, reject) => {
    mongoose.connect(DB_URL, { useUnifiedTopology: true, useNewUrlParser: true }).then(() => 
            feature = new FaeturesModel({
              name: featureName,
              description: featureDesc,
              catagory: featureCatagory,
              price: featurePrice + ' IQD' ,
              image: featureImage,
              dateOfCreation: new Date().toJSON().slice(0, 10).replace(/-/g, '/')
            })).then(() => {
      return FaeturesModel.updateOne({"_id" : id} , {$set : {feature}})
            .then(()=> feature.save())
          .then(() => {
            mongoose.disconnect();
            resolve()
          }).catch(err => {
            mongoose.disconnect();
            reject(err)
          })
        }
      )
})}

the problem is that the record is added as a new one without deleting the old one

2 Answers 2

1

Saving the document creates a new one. If you want to update something:

await Model.updateOne({ _id: doc._id }, { $set: { name: 'foo' } })

Basically remove the .then(()=> feature.save()) and it'll work.

This is from the documentation.

EDIT

Sorry, I forgot to mention that when you're updating, you don't create a new document like this new Feature() instead you say:

Model.updateOne({ _id: id }, { $set: req.body }).then(res => {
  // do stuff
})

Because new Feature() creates a new document with a new _id attached to it, so you can't update the existing document.

Hope it's clear now :D

EDIT 2

This is not part of the question, but use

const schema = new Schema({
  ...
},
{ timestamps: true });

in your schema instead

dateOfCreation: new Date().toJSON().slice(0, 10).replace(/-/g, '/')

It's easier to save creation date.

Sign up to request clarification or add additional context in comments.

3 Comments

i removed it and gave me an error says Performing an update on the path '_id' would modify the immutable field '_id' and from the code above i didnt update the _id
Try to use req.body instead of new Feature() when you update. So FaeturesModel.updateOne({"_id" : id} , {$set : {req.body}})
thanx bro it worked and I'll post the code below
0
exports.updateFeature = (id,featureName, featureCatagory, featurePrice , featureDesc , featureImage) => {
  return new Promise((resolve, reject) => {
    mongoose.connect(DB_URL, { useUnifiedTopology: true, useNewUrlParser: true }).then(() => 
            feature =({
              name: featureName,
              description: featureDesc,
              catagory: featureCatagory,
              price: featurePrice + ' IQD' ,
              image: featureImage,
              dateOfCreation: new Date().toJSON().slice(0, 10).replace(/-/g, '/')
            })).then(() => {
      return FaeturesModel.updateOne({'_id' : id} , {$set : feature})
            
          .then(() => {
            mongoose.disconnect();
            resolve()
          }).catch(err => {
            mongoose.disconnect();
            reject(err)
          })
        }
      )
})}```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.