[英]update data in mongodb using nodejs
I'm a beginner in NodeJS and mongodB and I'm using mongoose and trying to update data of product using this code我是 NodeJS 和 mongodB 的初学者,我正在使用 mongoose 并尝试使用此代码更新产品数据
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问题是记录被添加为新记录而不删除旧记录
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.基本上删除.then(()=> feature.save())
就可以了。
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:抱歉,我忘了提一下,当您更新时,您不会像这样new Feature()
创建一个新文档,而是说:
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.因为new Feature()
会创建一个附加了新_id
的新文档,所以您无法更新现有文档。
Hope it's clear now:D希望现在很清楚:D
EDIT 2编辑 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.保存创建日期更容易。
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)
})
}
)
})}```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.