简体   繁体   English

更新猫鼬中的一系列文档

[英]Update an array of documents in Mongoose

How can I update ALL documents in a collection where an attributes value needs to be different (a unique number) for each document? 在每个文档的属性值必须不同(唯一编号)的集合中,如何更新所有文档?

Below is my current code. 下面是我当前的代码。 This actually seems to update (I don't get an error) but the values in the db are not being updated. 这实际上似乎在更新(我没有收到错误),但是数据库中的值并未更新。

Model.find({}, function (err, docs) {

    if (err) {

        console.log(err);

    };



if(docs && docs.length > 0){


    for(var i=0; i<docs.length; i++){

    //SET NEW VALUE FOR EACH DOC - VALUE MUST BE UNIQUE TO EACH DOC
        docs[i].code = generateRandomCode();    

    }


    // PASS IN ARRAY OF UPDATED DOCS TO BE SAVED
    Model.update(docs, function (err, docs) {
        if (err) {
            console.log(err);
        }

        if(!err){   
            req.updatedSuccessfully = true;
        }

        return next();



    });


}
else{

    return next();

}


});

Before this I was trying to do something like this: 在此之前,我试图做这样的事情:

Model.update({}, { code: generateRandomCode() }, { multi: true }, function (err,      numberAffected, raw) {
  if (err) return handleError(err);
  console.log('The number of updated documents was %d', numberAffected);
  console.log('The raw response from Mongo was ', raw);
});

The problem with this is that generateRandomCode() is only called once but I need to create a different code for each document. 问题在于,generateRandomCode()仅被调用一次,但是我需要为每个文档创建不同的代码。 So neither of these example work. 因此,这些示例都不起作用。

Instead of trying model.update(), can you try to simply save the documents? 除了尝试使用model.update()之外,您还可以尝试简单地保存文档吗?

See answer to this question on this url: Update model with Mongoose, Express, NodeJS 在以下URL上查看此问题的答案: 用Mongoose,Express,NodeJS更新模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM