大家好,想询问下关于:findOneAndUpdate 的问题。 我这里使用了 mongoose。 我定义了一个 name 字段为唯一索引。导致每次我使用 findOneAndUpdate() 方法的时候,就算没有把 _id 赋值,该方法也会根据 name 查找到数据库已存在的文档。
代码如下,请各位老师帮忙看下,感谢!
import * as mongoose from 'mongoose';
import { Schema } from 'mongoose';
const tableName = 'test';
class StoreEntity {
_id: Schema.Types.ObjectId;
name: string;
}
const StoreSchema: Schema = new Schema({
name: {
type: String,
required: true
}
}, {
autoCreate: true,
versionKey: false
});
const StoreOperation = mongoose.model <StoreEntity> (tableName, StoreSchema, tableName);
insertOrUpdate(storeEntity: StoreEntity) {
const storeEntity = {
'name': 'test'
};
const query = { _id: storeEntity._id };
const update = {
name: storeEntity.name
}
const options = {
upsert: true,
new: true
};
StoreOperation.findOneAndUpdate(query,
update,
options,
(e, writeResult) => {
if (e) {
console.error(`save: ${storeEntity} error`, e);
rejected(e);
} else {
resolved(writeResult);
}
});
}
const storeEntity = new StoreEntity();
storeEntity.name = 'test';
insertOrUpdate(storeEntity);