使用Mongoose和Node

时间:2017-04-18 14:45:55

标签: node.js mongoose updating

我有一个包含一系列子文档的模型。这是Company

{
"_id" : ObjectId(":58be7c236dcb5f2feff91ac0"),
"name" : "sky srl",

"contacts" : [ 
    {
        "_id" : ObjectId("58be7c236dcb5f2feff91ac2"),
         "name": { type: String, required: true },
        "company" : ObjectId("58be7c236dcb5f2feff91ac0"),
        "email" : "sky@gmail.com",
        "chatId" : "",
        "phone" : "123456789",
        "name" : "John Smith"
    },
    {
        "_id" : ObjectId("58be7f3a6dcb5f2feff91ad3"),
        "company" : ObjectId("58be7f3a6dcb5f2feff91ad1"),
        "email" : "beta@gmail.com",
        "chatId" : "",
        "phone" : "987654321",
        "name" : "Bill Gaset"
    } 
],
    "__v" : 1
}

我有几家公司,我想更新所有公司中与我正在搜索的phone匹配的所有联系人的字段chatId。

我的架构定义(简化,专注于问题):

var contactSchema = new Schema({
[...]
phone: { type: String, required: true },
email: { type: String },
chatId: { type: String },
company: Schema.Types.ObjectId,
});

var companySchema = new Schema({

name: { type: String, required: true },
type: { type: String, default: "company" },
contacts: [contactSchema]
});

我试过

var conditions = { "contacts.phone": req.body.phone };
var partialUpdate = req.body; //it contains 'req.body.phone' and 'req.body.chatId' attributes
Company.find(conditions).then(
        function (results) {
            results.map( function(companyFound) {
                companyFound.contacts.forEach(function (contactContainer){

                    if (contactContainer.phone == partialUpdate.phone) {
                        contactContainer.chatId = partialUpdate.chatId;

                        Company.save();
                        companyFound.save();
                        contactContainer.save();
                        results.save();
                    }

                    //not sure of what to save, so i save everything
                    companyFound.save();
                    contactContainer.save();
                    results.save();
                });
            });
});

遵循answer;但它不起作用。它没有保存任何东西,我做错了什么?

2 个答案:

答案 0 :(得分:1)

我以前从未这样做过,但值得一试。

也许你需要使用$elemMatch

// find the companies that have contacts having the phone number
Company.find().where('contacts', { $elemMatch: { phone: req.body.phone }}).exec(function (err, companies) {
    if (err) {
        console.log(err);
        return;
    }
    // see if you can at least get the query to work
    console.log(companies);
    async.eachSeries(companies, function updateCompany(company, done) {
        // find and update the contacts having the phone number
        company.contacts.forEach(function (contact, i, arr) {
            if (contact.phone == req.body.phone) {
                arr[i].chatId = req.body.chatId;
            }
        });
        company.save(done);
    }, function allDone (err) {
        console.log(err);
    });
});

注意,我正在使用async.js对多个项目执行异步操作。

老实说,我会简单地将contacts数组Contact references - 更容易查询和更新。

答案 1 :(得分:1)

仅供记录:我这样做是为了让它在没有async.js的情况下工作:

Company.find().where('contacts', { $elemMatch: { phone: req.body.phone } })
            .exec(function (err, companies) {
                if (err) {
                    console.log(err);
                    return;
                }
                console.log("companies: " + JSON.stringify(companies, null, 4));

                companies.forEach(function (company) {
                    company.contacts.map(function (contact, i, arr) {
                        if (contact.phone == req.body.phone) {
                            arr[i].telegramChatId = req.body.telegramChatId;
                        }
                    });
                    company.save();
                }, 
                function allDone(err) {
                    console.log(err);
                });
            });`