【问题标题】:How to update some data based on array value in Mongoose?如何根据 Mongoose 中的数组值更新一些数据?
【发布时间】:2018-11-28 12:12:02
【问题描述】:

我想通过使用我之前找到的数组值来更新 Mongoose 中的一些数据。

Company.findById(id_company,function(err, company) {
    if(err){
        console.log(err);
        return res.status(500).send({message: "Error, check the console. (Update Company)"});
    }
    const Students = company.students;
    User.find({'_id':{"$in" : Students}},function(err, users) {
        console.log(Students);
        // WANTED QUERY : Update company = null from Users where _id = Students[];
    });
});

Students 在包含对象的数组中返回 users._id,我用它来查找 users 对象,然后我想将 users 对象中的一个字段设置为 null,该字段名为“company”。我怎么能这样做?谢谢。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    根据您发布的内容(我冒昧地使用Promises,但您可以通过回调大致实现相同的目的),您可以执行以下操作:

        User.find({'_id':{"$in" : Students}})
            .then( users =>{
                return Promise.all( users.map( user => {
                    user.company = null;
                    return user.save()
                }) );
             })
             .then( () => {
                 console.log("yay");
             })
             .catch( e => {
                 console.log("failed");
             });
    

    基本上,我在这里所做的是确保正确保存.find() 调用返回的.all() 用户模型,方法是检查为.save() 每个返回的Promised 值。 如果其中一个因某种原因失败,Promise.all() 会返回拒绝,您可以事后处理。

    但是,在这种情况下,每个项目都将映射到对您的数据库的查询,这是不好的。更好的策略是使用Model.update(),这将在本质上减少数据库查询。

    User.update({
        '_id': {"$in": Students}
    }, {
        'company': <Whatever you want>
    })
    .then()
    

    【讨论】:

      【解决方案2】:

      使用.update,但请确保您通过选项{multi: true} 类似:

      User.update = function (query, {company: null}, {multi: true}, function(err, result ) { ... });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多