提问者:小点点

如何从NodeJS Sequelize.save()方法返回最后一个插入ID


给出这个例子,

// insert the conversation into the lookup
const LOOKUP = new PrivateMessageLookup;

LOOKUP.communicator1 = communicator1;
LOOKUP.communicator2 = communicator2;

LOOKUP.save();

其中privateMessageLookup是模型

lookup.save()正确插入记录,但如何获取该记录的插入ID?

我找不到答案。


共1个答案

匿名用户

当您使用Model.create()函数时,它将返回一个已设置ID的模型实例。这是构建一个新对象,指定它是一个新记录,然后保存它的捷径。

// create a new instance from the model
const lookup = await Lookup.create({ communicator1, communicator2 });
// the ID will populate
console.log(lookup.id);

长程版本:

// build the record, specify it is new
const lookup = Lookup.build({ communicator1, communicator2 }, { isNewRecord: true });
// save
await lookup.save();
// the ID will populate
console.log(lookup.id);