Reputation: 1
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
Upvotes: 0
Views: 50
Reputation: 1
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)
})
}
)
})}```
Upvotes: 0
Reputation: 812
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.
Upvotes: 1