我尝试使用 MongoDB 和 Node express 创建 API(第一次在 node.js 中)。
我做了以下路由,旨在使用 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 输入中有重复项,则只会创建唯一的文档。 我想这种“问题”很常见,但我没有找到任何资源来解决它。
感谢您的帮助
答案 0 :(得分:1)
您的 save
没有被等待,因此您可能会遇到这样一种情况:一个文档尚未保存,而循环继续处理其他 JSON 文档,可能与正在保存的文档相同。< /p>
使用 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);
}