![](/img/trans.png)
[英]Having trouble inserting documents in mongoDB using mongoose and node.js
[英]Fail to insert JSON into mongoDB using mongoose in Node.js
我无法在node.js中使用猫鼬更新我的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')
}
当您使用save()方法时,有时Mongoose不知道发生了什么变化。 您可以使用markModified()将数组标记为已修改:
b.content.page.push(page);
b.markModified('content');
b.save(function (err) { .... })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.