[英]Mongoose : filter then update document if it exists , otherwise create it
[英]Mongoose create multiple document if not exists
我尝试使用 MongoDB 和 Node express(第一次在 node.js 中)创建一个 API。
我做了以下路线,旨在使用 JSON 输入(来自外部请求)在 mongoDB 中保存多个文件(唯一):
router.post('/sessions', function (req, res, next) {
// invoke sessions update
var config = {
method: 'get',
url: 'https://blabla',
headers: {
'Accept': 'application/json;version=0.1',
'Accept-Language': 'fr',
}
};
axios(config)
.then(function (response) {
for (const session of response.data) {
doc = UserSimple.findOne({id: session.recipient.id}).then(function (doc) {
if (!doc) {
var newUser = new UserSimple(session.recipient)
newUser.save()
}
})
}
})
.catch(function (error) {
console.log(error);
});
});
从我的代码来看,我似乎没有正确理解“承诺”,因为我的代码尝试获取所有文档,然后将其保存(因为做出承诺时不存在)它在 MongoDB 中:
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11676365 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 481020 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 146299 }, { projection: {} })
Mongoose: usersimples.findOne({ id: 11427231 }, { projection: {} })
Mongoose: usersimples.insertOne({ _id: ObjectId("60b8910526436428a409f6a9")....., id: 11676365 })
...
Mongoose: usersimples.insertOne({ _id: ObjectId("60b8910526436428a409f6ab")....., id: 11676365 })
我想要做的是,检查MongoDB中是否存在一个文件,如果没有则创建它; 因此,在同一个“请求”中,如果我的 JSON 输入中有重复项,则只会创建唯一的文档。 我想这种“问题”很常见,但我没有找到任何资源来解决它。
谢谢您的帮助
不等待您的save
,因此您最终可能会遇到一个文档尚未保存的情况,而循环继续处理其他 JSON 文档,可能与正在保存的文档相同。
使用 async/await 重写:
try {
const response = await axios(config);
let doc;
for (const session of response.data) {
doc = await UserSimple.findOne({ id: session.recipient.id });
if (!doc) {
var newUser = new UserSimple(session.recipient);
await newUser.save();
}
}
} catch (error) {
console.log(error);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.