nestjs 和更新集合后返回承诺的问题



我有这些模式:

Foo系列与Bar有一对多关系:

@Schema()
export class Foo {
@Prop()
attr1: number;
@Prop({ type: mongooseSchema.Types.ObjectId, ref: 'Bar' })
bar: Bar;
}
export const FooSchema = SchemaFactory.createForClass(Foo);
@Schema()
export class Bar {
@Prop()
name: string;
@Prop()
firstName: string;
@Prop([{ type: mongooseSchema.Types.ObjectId, ref: Foo.name }])
foos: Foo[];
}
export const BarSchema = SchemaFactory.createForClass(Bar);

我正试图使用Mongoose和nestjs在我的Mongodb中保存一个新的Foo。在我的foo.service.ts中,我有这样的:

@Injectable()
export class FooService {
constructor(
@InjectModel(Foo.name) private fooModel: Model<FooDocument>,
@InjectModel(Bar.name) private barModel: Model<BarDocument>,
) {}
// this works but doesn't save the related foos in Bar.foos[]
// async create(foo: Foo): Promise<Foo> {
//   const newFoo = new this.fooModel(foo);
//   return await foo.save();
// }
async create(foo: Foo): Promise<Bar> {
const newFoo = new this.fooModel(foo);
const savedFoo = newFoo.save().then(function (f) {
return this.barModel.findByIdAndUpdate(f._id, {
$push: { foos: f._id },
});
});
}
}

我知道我的第一个方法(注释掉的方法(有效,并且模式保存正确,因为在Mongo上的Foo类中,我在D中看到了对正确Bar对象的ObjectId引用。然而,Bar.Foo数组仍然为空。我似乎明白,在Mongo中,我需要将我刚刚保存的新Foo对象的引用推送到Bar.Foo数组中。所以我用mongoose检索相应的Bar对象,通过推送foo来更新它_id。

但我得到了:

- error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

在服务器启动之前。。。。我做错了什么?

您在这个函数中缺少return语句,因为您声明了它的返回类型必须是Promise<Bar>

async create(foo: Foo): Promise<Bar> {
const newFoo = new this.fooModel(foo);
const savedFoo = newFoo.save().then(function (f) {
return this.barModel.findByIdAndUpdate(f._id, {
$push: { foos: f._id },
});
});
}

最新更新