水线插入与 return id 的一对多关联
Waterline insert one to many association with return id
我有两个模型,文档和文件,每个文档可以有很多文件,而每个文件只能属于一个文档(一对多)。
我有以下代码试图插入一个文件。 Waterline 将 return 带有所有关联文件的文档模式,但我想要的只是我刚刚插入的文件的最后一个插入 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()
只是 returns model
的填充版本。您可以看到 model.files
中的所有文件,但接下来由您决定哪个是最后一个文件。
一种替代方法是在将文件添加到文档之前创建该文件。你应该能够做到:
//...
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。在性能方面,它应该与内部水线相同,必须以类似的方式创建文件。
我有两个模型,文档和文件,每个文档可以有很多文件,而每个文件只能属于一个文档(一对多)。
我有以下代码试图插入一个文件。 Waterline 将 return 带有所有关联文件的文档模式,但我想要的只是我刚刚插入的文件的最后一个插入 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()
只是 returns model
的填充版本。您可以看到 model.files
中的所有文件,但接下来由您决定哪个是最后一个文件。
一种替代方法是在将文件添加到文档之前创建该文件。你应该能够做到:
//...
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。在性能方面,它应该与内部水线相同,必须以类似的方式创建文件。