如何使用基于_id的Mongoose进行upsert?

Sha*_*oon 3 upsert mongoose mongodb node.js coffeescript

当我这样做:

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
Run Code Online (Sandbox Code Playgroud)

除了null _id字段外,它将创建一个新的客户记录.我假设这是因为upsert的插入部分看起来query要创建文档.我怎么能这样做,如果没有找到doc,那么插入一个新的ObjectId

Han*_*son 8

不确定你是否已经想出了这个,但如果你不想遇到像上面提到的Mustafa这样的独特键约束的麻烦,我做的方法是使用mongoosefindByIdAndUpdate:

// 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
Run Code Online (Sandbox Code Playgroud)

我从来没有写过CoffeeScript,所以请原谅我,如果有些语法错了,但我认为我应该做的很明显.

需要注意的一点是,您需要确保client_id既不是空字符串(因为这会导致'无效的ObjectID'错误)也不是null(因为mongoose似乎从您要查询的那个中推断出新文档的id).如果是,我创建一个新的ObjectId,这会导致查询错过,因此我创建了一个带有该ID的新文档,因为我传递了{upsert:true}.

这似乎解决了我的问题.