Mongoose文档更新错误 [英] Mongoose document update error
问题描述
使用节点
和 mongoose
最近,我喜欢它,直到我不得不更新一个模型。
Been working with node
and mongoose
lately and I enjoyed it until I had to update a model.
这里是我在做什么:
module.exports.update = (post, cb) ->
Post.update _id: post._id, post, (err, data) ->
cb(err, data)
所以我认为这将是一个简单的保存一个新的帖子,但它抱怨
与错误:
So I thought it'll be a easy as saving a new post but it's complaining with error:
错误:'不允许'_id'
err: 'Mod on _id not allowed'
我试图删除 post._id
,然后将其传递给我的更新方法,但它没有工作和I
找不到任何好的例子,如何做,除了一个看起来
a位奇数,首先你找到 Post
通过 _id
,然后手动更新每个键
并保存重新发布...
I tried to delete post._id
before passing it to my update method, but it didn't work and I
couldn't find any good examples on how to do it except one that looks
a bit odd where first you find Post
by _id
, then update each key
manually and save Post back again...
p>
推荐答案
您在正确的轨道上删除 post._id
到更新
。假设 post
是一个纯JS对象,这应该工作:
You were on the right track with deleting post._id
before passing it to update
. Assuming post
is a plain JS object, this should work:
module.exports.update = (post, cb) ->
id = post._id
delete post._id
Post.update _id: id, post, (err, data) ->
cb(err, data)
这篇关于Mongoose文档更新错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!