// 我在用户Schema中创建了专栏数组(articles),专栏是对象,底下articles数组嵌套了文章对象,结构类似下图:
// User.articles = [专栏一, 专栏二 ...]
// 专栏一.articles = [ 文章一, 文章二 ...]
// 实际操作中,只要涉及到修改原有值,一保存就报错
// 如splice,pop,或者直接赋值都报错,但push就成功
// 找到专栏,对专栏文章进行splice可以成功修改,但保存操作时报错
user.articles[cindex].articles.splice(aindex, 1, newarticle) // cindex 专栏序号 aindex 文章序号
id = column.articles[aindex]._id
console.log("发布文章更新,id为:", id) // 能输出结果
user.save()
// 可成功修改,保存报错
user.articles[cindex].articles[aindex].name = 'asdfsadf'
user.save()
// 成功
column.articles.push({
_id : column.articles[aindex]._id,
name: 'asdfsdf'
})
user.save()
// 报错如下:
// Unhandled rejection Error
// at model.wrappedPointCut [as save] (C:\nodejs\myblog\node_modules\mongoose\lib\services\model\applyHooks.js:111:29)
// at User.findOne.then.user (C:\nodejs\myblog\models\UserActions.js:299:10)
// at tryCatcher (C:\nodejs\myblog\node_modules\bluebird\js\release\util.js:16:23)
// at Promise._settlePromiseFromHandler (C:\nodejs\myblog\node_modules\bluebird\js\release\promise.js:512:31)
// at Promise._settlePromise (C:\nodejs\myblog\node_modules\bluebird\js\release\promise.js:569:18)
// at Promise._settlePromise0 (C:\nodejs\myblog\node_modules\bluebird\js\release\promise.js:614:10)
// at Promise._settlePromises (C:\nodejs\myblog\node_modules\bluebird\js\release\promise.js:693:18)
When I use save(err=>console.log(err))
, a versionkey error is reported. Then I disable versionkey and temporarily prevent this error from occurring.
But after all, I still haven’t figured out the cause of this problem. Please also explain in detail.
You need to use relevant methods to modify and save database data. You cannot directly operate the data attributes. Use save when finished
save method has parameters