Mongodb Mongoose findOneAndUpdate在模型上

Mongodb Mongoose findOneAndUpdate在模型上,mongodb,mongoose,mongoose-schema,Mongodb,Mongoose,Mongoose Schema,如果我使用findOneAndUpdate调用进行upsert,那么猫鼬模式的用途是什么 我能找到的一切似乎都表明,如果我执行findOneAndUpdate,我需要引用基本模式而不是实例 以下是我的设置: const PersonSchema = new mongoose.Schema({ ssn: { type: Number, unique: true, }, first: String, last: String }) const Person = mo

如果我使用
findOneAndUpdate
调用进行upsert,那么猫鼬模式的用途是什么

我能找到的一切似乎都表明,如果我执行
findOneAndUpdate
,我需要引用基本模式而不是实例

以下是我的设置:

const PersonSchema = new mongoose.Schema({
  ssn: {
    type: Number,
    unique: true,
  },
  first: String,
  last: String
})

const Person = mongoose.model("Person", PersonSchema)
const person = new Person({ssn: 123456789, first: "Foo", last: "Bar"})
如果我只是保存(并且ssn已经存在,我将得到一个“唯一”冲突)

相反,我发现我需要做一些事情,比如

const options = { upsert: true, new: true }
const query = { ssn: 123456789 }

Person.findOneAndUpdate(
  query,
  {
    ssn: 123456789,
    first: "Foo",
    last: "Bar"
  },
  options)

const options = { upsert: true, new: true }
const query = { ssn: 123456789 }

const newPerson = Object.assign({}, person._doc)

// delete this so I don't get a conflict with Mongoose on the _id during insert
delete newPerson._id

Person.findOneAndUpdate(query, newPerson, options)
似乎
findOneAndUpdate
并不关心特定的模型(或实例),它只是一种访问底层MongoDB方法的机制

是这样吗?还是我遗漏了一些显而易见的东西

const options = { upsert: true, new: true }
const query = { ssn: 123456789 }

const newPerson = Object.assign({}, person._doc)

// delete this so I don't get a conflict with Mongoose on the _id during insert
delete newPerson._id

Person.findOneAndUpdate(query, newPerson, options)