【发布时间】:2015-09-20 15:16:17
【问题描述】:
我在 node.js 中使用 mongoose 更新我的 mongoDB 失败
这是我的架构:
var bookSchema = mongoose.Schema({
_creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
content: JSON,
views: Number,
name: String,
genre: String,
Description: String,
dateOfCreation: Date,
published: Boolean
})
所以“内容”是一个 JSON 元素。 在之前的查询中,我将以下 JSON 插入到“内容”中:
{
"author": "AuthorName",
"series": "SeriesNameIfPartOfASeries",
"name": "NameOfBook",
"page": []
}
我的问题是我在编辑 JSON 后无法更新数据库。
我正在尝试将其添加到页面数组中:
{
"img": "urlOfImage",
"frame": [{
"id": "0",
"cx": "0",
"cy": "0",
"scale": "1",
"rotation": "0",
"filters": "",
"transition":
{
"type": "move",
"time": "0",
"easing": "linear"
},
"requireUserInput": "true",
"cropping":
{
"visible": "false",
"shape": "rect",
"color": "rgb(0,0,0)",
"opacity": "1",
"x": [],
"y": []
}
}]
}
由于某种原因,以下代码不会引发任何错误,但不会更新数据库。 此外,如果我在 b.save() 函数中使用 console.log(b.content),它似乎已经更新了它,但我的数据库保持不变。
function (req,res) {
Book.findOne({_id: req.body.bookID, _creator: req.user._id },function (err, b) {
if (err)
throw(err)
var page = {
"img": req.files.file.name,
"frame": [{
"id": "0",
"cx": "0",
"cy": "0",
"scale": "1",
"rotation": "0",
"filters": "",
"transition":
{
"type": "move",
"time": "0",
"easing": "linear"
},
"requireUserInput": "true",
"cropping":
{
"visible": "false",
"shape": "rect",
"color": "rgb(0,0,0)",
"opacity": "1",
"x": [],
"y": []
}
}]
}
b.content.page.push(page)
b.save(function (err) {
if(err)
throw(err)
//the following returns the book WITH the right data. What is going
//on?
console.log(b.content)
})
}
编辑 1: --------------------------------------
尝试使用 markModified() 仍然不起作用。这是我的更新代码和建议的解决方案:
function (req,res) {
Book.findOne({_id:req.body.bookID, _author: req.user._id},function(err,b) {
if(err)
throw(err);
if(b) {
var page = {
"img": req.files.file.name,
"frame": [{
"id": "0",
"cx": "0",
"cy": "0",
"scale": "1",
"rotation": "0",
"filters": "",
"transition":
{
"type": "move",
"time": "0",
"easing": "linear"
},
"requireUserInput": "true",
"cropping":
{
"visible": "false",
"shape": "rect",
"color": "rgb(0,0,0)",
"opacity": "1",
"x": [],
"y": []
}
}]
}
b.content.page.push(page)
b.markModified('content')
b.save(function (err) {
if(err)
throw(err);
})
}
})
res.end('200')
}
【问题讨论】:
-
有没有JSON类型的mongoose版本?