gpt4 book ai didi

mongodb - 我如何根据 _id 使用 Mongoose 进行更新?

转载 作者:可可西里 更新时间:2023-11-01 09:20:01 29 4
gpt4 key购买 nike

当我这样做时:

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 的插入部分查找 query 来创建文档。我该怎么做才能在找不到文档时插入新的 ObjectId

最佳答案

不确定您是否已经解决了这个问题,但是如果您不想遇到像上面提到的 Mustafa 这样的唯一键约束的麻烦,我的方法是使用 mongoose 的 findByIdAndUpdate :

// require mongoose

client_id = req.param("client_id") ? new mongoose.Types.ObjectId
client =
name: req.param "clientName"
status: 'active'

Client.findByIdAndUpdate client_id, client, {upsert: true}, (err, updRes) ->
if err
res.json
error: "Couldn't create client"
else
res.json client

我从来没有写过 CoffeeScript,所以如果其中的某些语法有误,请原谅我,但我认为我想做的事情应该很明显。

需要注意的一件事是您需要确保 client_id 既不是空字符串(因为这会导致“无效的 ObjectID”错误)也不是 null(因为 mongoose 似乎从您正在查询的文档中推断出新文档的 ID为了)。如果是,我会创建一个新的 ObjectId,这将导致查询丢失,因此会创建一个具有该 ID 的新文档,因为我传递了 {upsert: true}。

这似乎已经解决了我的问题。

关于mongodb - 我如何根据 _id 使用 Mongoose 进行更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8490519/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com