我正试图用这个Schema将标签添加到MongoDB集合中的现有标签中。
const workSchema = new mongoose.Schema({
title: {
type: String,
required: "Tile can't be blank"
},
description: {
type: String
},
imageURL: {
type: String,
unique: true
},
workURL:{
type: String,
unique: true
},
tags:{
type:Array
},
createdDate: {
type: Date,
default: Date.now
}
});
const Work = mongoose.model('Work', workSchema);
module.exports = Work;
我做了一个API,向 "apiwork:workIdtags "发出PUT请求。
exports.updateTags = (req, res) =>{
try{
const newTags = req.body.tags.split(',');
newTags.forEach(tag => {
db.Work.update(
{"_id": req.params.workId},
{
$push:{
tags: tag
}
}
)
})
res.status(200).send({message : "tags updated"})
}
catch(error){
res.status(400).send(error)
}
}
request.body。
{
tags:"a,b,c"
}
问题是数组不能用新的标签值更新。
我在文档和网络上搜索了其他的更新方法,但我没有找到任何解决方案。
你还没有定义 _id
在你 workSchema
所以,该类型 _id
将是 ObjectId
但是 req.params.workId
可能是 String
,所以查询一个 ObjectId
附带 String
不会工作。
所以你应该转换 req.params.workId
到 ObjectId
使用 mongoose.Types.ObjectId
{ "_id": mongoose.Types.ObjectId(req.params.workId) }
但你可以通过使用以下方法来改进你的代码 .findByIdAndUpdate
和 $each
经营者
.findByIdAndUpdate
将自动转换您的 _id
到 ObjectId
$each
到 $push
同时使用多个数组元素,而无需使用 .forEach
Work.findByIdAndUpdate(req.params.workId, {
$push: { "tags": { $each: newTags } }
})