【发布时间】:2021-01-22 03:20:13
【问题描述】:
我正在尝试将一个新文档保存到 MongoDB 中,该文档具有对另一个集合的引用,以便获取我使用 find 的所有引用的 ObjectId,以便在保存之前获取它们。我需要等待查找完成才能继续,但我无法让它工作。我认为这与承诺有关,但我无法弄清楚。如果我没有清楚地解释这一点,我在下面有一个例子。任何帮助将不胜感激!
人物架构
const personSchema = new Schema(
{
name: { type: String, required: true },
fruits: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Fruit' }]
}
)
水果模式
const fruitSchema = new Schema(
{
name: { type: String, unique: true, required: true },
}
)
添加代码
router.route('/add').post((req, res) => {
const name = req.body.name;
let fruits = [];
Fruit.find({ name: { $in: req.body.fruits }}, (err, foundFruits) => {
if (err) res.send(err)
foundFruits.forEach(fruit => {
fruits.push(fruit._id);
});
});
const newPerson = new Person({ name, fruits });
newPerson.save()
.then(() => res.json('Person added')
.catch(err => res.status(400).json('Error: ' + err));
}
示例: 我想添加一个名为“Bob”的人,并引用“banana”和“apple”(假设已在数据库中添加),所以我发出一个 POST 请求,其主体为...
{
"name": "Bob",
"fruits": ["banana", "apple"]
}
添加后,当我检查我的数据库时,该条目存在,但“水果”有一个空数组,而不是对“香蕉”和“苹果”的引用。
【问题讨论】: