我是js (typescript, mongoDB, node.)的新手
我刚刚发现我的代码不像我预期的那样,我在mongoDB上得到6个寄存器,而不是一个,它应该检查寄存器是否存在,然后更新它,我不知道它是否与await/async有关,或者我做错了什么,提前感谢,这是我的代码。
fields.forEach((value) => {
try {
const mongoConnection = new DocumentDbRepository();
let checksIfExists = await mongoConnection.getValue(key, information[uniqueValue]);
if(checksIfExists==null){
let insert = await mongoConnection.insertValue(information);
console.log(insert);
}
if(checksIfExists?.passValue===information.passValue){
console.log('---------update---------');
let sons = Object.values(information.ticketToRide);
information.ticketToRide = sons;
let update = await mongoConnection.updateRegister(information, checksIfExists._id);
console.log(update);
} else {
console.log('---------insert---------');
let sons = Object.values(information.ticketToRide);
information = sons;
let insert = await mongoConnection.insertValue(information);
console.log(insert);
}
} catch (error) {
console.log(error)
}
}
async getValue(uniqueValue: any, keyValue:any) {
if (this._connection == null) {
await this.connect();
}
const db = this._connection.db(DocumentDbRepository.DbName);
const ticketToRide = db.collection("ticketToRide");
const query = {};
query[uniqueValue] = ''+keyValue+'';
const passInfo = await ticketToRide.findOne(query);
return passInfo;
}
async insertValue(information: any) {
if (this._connection == null) {
await this.connect();
}
const db = this._connection.db(DocumentDbRepository.DbName);
const ticketToRide = db.collection("ticketToRide");
let check = await ticketToRide.insertOne(
information
)
return check;
}
首先,您不需要在循环中创建连接。
第二,mongodb有一个update()或updateMany()方法,它有一个特殊的选项{ upsert: true }
。如果通过了,则自动插入。
使用例子:
Person.update( { name: 'Ted' }, { name: 'Ted', age : 50 }, { upsert: true })