【问题标题】:Mongoose waiting for find to finish before saving猫鼬在保存前等待查找完成
【发布时间】: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"]
}

添加后,当我检查我的数据库时,该条目存在,但“水果”有一个空数组,而不是对“香蕉”和“苹果”的引用。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    问题是来自find 方法的回调需要一些时间来执行,然后您的其余代码完成运行。您要做的是等待承诺,以便代码按预期执行:

    router.route('/add').post(async (req, res) => {
        const name = req.body.name;
        let fruits = [];
    
        let foundFruits = await Fruit.find({ name: { $in: req.body.fruits }});
        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));
    }
    

    因为您只使用水果中的_id,所以使用distinct 可以更优雅地完成:

    router.route('/add').post(async (req, res) => {
        const name = req.body.name;
    
        let fruits = await Fruit.distinct("_id", { name: { $in: req.body.fruits }});
        const newPerson = new Person({ name, fruits });
        newPerson.save()
            .then(() => res.json('Person added')
                .catch(err => res.status(400).json('Error: ' + err));
    }
    

    【讨论】:

    • 啊,我会阅读更多关于 distinct 的内容,从来不知道。非常感谢!
    猜你喜欢
    • 2019-03-20
    • 2016-11-19
    • 2018-11-29
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2018-08-30
    • 2016-11-04
    相关资源
    最近更新 更多