如何根据 _id 使用 Mongoose 更新插入?
当我这样做时:
client_id = req.param("client_id") ? null
client =
name: req.param "clientName"
status: 'active'
Client.update {_id: client_id}, client, {upsert: true}, (err, updRes) ->
if err
res.json
error: "Couldn't create client"
else
res.json client
它将创建一个新的客户记录,但带有 null
_id
字段的记录除外。我认为这是因为 upsert 的插入部分会查找查询
来创建文档。我该如何做到这一点,以便在找不到文档的情况下插入新的 ObjectId
?
When I do this:
client_id = req.param("client_id") ? null
client =
name: req.param "clientName"
status: 'active'
Client.update {_id: client_id}, client, {upsert: true}, (err, updRes) ->
if err
res.json
error: "Couldn't create client"
else
res.json client
It will create a new client record, except with a null
_id
field. I assume that's because the insert part of the upsert looks to the query
to create the document. How can I do it so that if no doc is found, then insert a new ObjectId
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定您是否已经弄清楚了这一点,但如果您不想遇到像上面提到的 Mustafa 这样的独特键约束的麻烦,我的方法是使用 mongoose 的 findByIdAndUpdate:
我从来没有写过 CoffeeScript,所以请原谅我,如果其中一些语法是错了,但我认为我想要做什么应该是相当明显的。
需要注意的一件事是,您需要确保 client_id 既不是空字符串(因为这会导致“无效的 ObjectID”错误)也不是 null(因为 mongoose 似乎从您正在查询的文档推断出新文档的 id)。如果是这样,我将创建一个新的 ObjectId,这将导致查询丢失,并因此在我传递 {upsert: true} 后使用该 ID 创建一个新文档。
这似乎已经解决了我的问题。
Not sure if you have figured this one out yet, but in case you don't want to run into trouble with unique key constraints like Mustafa mentioned above, the way I've done it is by using mongoose's findByIdAndUpdate:
I've never written CoffeeScript, so forgive me if some of that syntax is wrong, but I think it should be fairly obvious what I'm trying to do.
One thing to notice is that you need to make sure client_id is neither an empty string (as that would cause an 'Invalid ObjectID' error) nor null (because mongoose seems infer the new document's id from the one you're querying for). In case it is, I create a new ObjectId, which will cause the query to miss and therefore create a new document with that ID since I pass {upsert: true}.
This seems to have solved the problem for me.
使用 Mongoose 所需要做的就是在客户端调用 save,Mongoose 会自行判断是更新还是插入:
注意:客户端是 Mongoose 模型。
All you have to do with Mongoose is to call save on the client, Mongoose will figure out on its own if it's an update or an insert:
Note: Client is a Mongoose model.