javascript - In mongoose, how can i check if all elements in an ObjectId Array exists on database
问题描述
Im working on a NodeJS RESTful API, using mongoose and MongoDB of course.
I have a mongoose model like this
const mySchema = mongoose.Schema({
_id: {type: mongoose.Schema.Types.ObjectId},
Cities: [{type: mongoose.Schema.Types.ObjectId, ref: 'City'}]
}
and a route like this
router.post('/', (req, res, next) => {
for (const cityId of req.body.cities) {
City.findById(cityId)
.then(city => {
if (!city) {
return routingResult.NotFound(res, "One city doesnt exists.");
}
})
.catch(err => {
console.error(err);
routingResult.Error(res, err);
});
As you can see, i'm trying to check if ALL of the elements on req.body.cities array exists on Database before i create a new document and save it.
I need to know if there's a way to check all elements at the same time. (those elements are ObjectID's that references another collection on my DB), something like City.find({"$all":req.body.cities})
... i know this is not the proper implementation, i just want to know if there's something like that.
If any of the objectId's doesn't exists i must not create the new document to be inserted on Cities collection.
Is there a way to achieve this ?
解决方案
推荐阅读
- javascript - 即使文件上传完全完成,网站也会让用户等待
- python - 如何从pickle加载的文件中访问特定的字符串?
- javascript - Flask - 将 sqlite 查询到 javascript
- java - Android Studio 中的 R.id 是什么?
- wcf - 如何在 IIS 托管的 WCF 应用程序中配置 AutoMapper 9.0
- c++ - C++ 打印向量并替换缺失的元素
- javascript - 如何在 React 导航到新路线之前更改滚动位置?
- android - 我需要在工具栏上添加一个自定义按钮而不是常规的 3 点菜单
- node.js - Typescript 路径别名在运行时未正确解析
- python - 使用 python 创建 SQLite 数据库时出现意外错误