【发布时间】:2020-05-11 01:57:35
【问题描述】:
我正在尝试使用此架构将标签添加到 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/work/:workId/tags”发出 PUT 请求的 API
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"
}
问题是数组不会用新的标签值更新
我在文档和网络上搜索了其他更新方式,但没有找到任何解决方案。
【问题讨论】:
标签: javascript node.js mongoose mongoose-schema