水线插入一对多关联与返回ID

我有两个模型,文档和文件,每个文档可以有许多文件,而每个文件只能属于一个文档(一对多)。

我有以下代码试图插入一个文件。 水线将返回与所有相关文件的文档模式,但我想要的只是我刚刚插入的文件的最后一个插入ID。

Document.findOne({hash: documentHash}).exec(function(err, document) { if (err) {return res.serverError(err);} document.files.add({ name: req.param("name"), creator: req.param("userID"); }); document.save(function(err, model) { if (err) {return res.serverError(err);} //it returned the Document modal, but I want the last insert id console.log(model); res.send(1); }); }); 

我怕document.save()只返回model的填充版本。 你可以在model.files看到所有的文件,但是这将由你决定哪个是最后一个。

一种替代方法是在将文件添加到文档之前创build该文件。 你应该可以做到:

 //... File.create({ name: req.param("name"), creator: req.param("userID"); }, function(err, file){ if (err) {return res.serverError(err);} var newFileId = file.id; document.files.add(file.id); document.save(function(err, model) { if (err) {return res.serverError(err);} // the Document modal console.log(model); // the last insert id console.log('last inserted id:', newFileId); res.send(1); }); }); //... 

在这种情况下, newFileId将有你需要的ID。 性能方面应该与内部水线相同,必须以类似的方式创build文件。