如何将一个集合的数据转移到另一个mongodb的集合中?

问题描述 投票:0回答:1

我正在使用nestjs.我有两个集合,一个是订单,另一个是付款,我想从订单集合中检索一个单一的条目,并将同一条目保存到付款集合中。

下面是服务的代码。

async order(name){
    const list=this.usersmodel.find({name:name}).exec()
    //return list
    try{
        if(list){
            const x=this.usersmodel.aggregate([
                {$out:"payment"}
            ])
            return "data saved in payment collection"
        }
    }
    catch(error){
        return(error.message)
    }
}

这里是控制器的代码。

@Get('orderdata')
async orderdata(@Body('name')name){
    return this.usersService.order(name)
}

通过使用这些代码,我既没有得到想要的输出,也没有得到任何错误。当我在postman中点击API时,我得到了 "data saved in payment collection",但我没有得到我的付款集合中的条目。

mongodb typescript postman nestjs
1个回答
1
投票

我认为问题出在这里,在这一行中

const list = this.usersmodel.find({ name: name }).exec()

这是 asynchronous 的代码块,所以接下来的行将被执行,而不需要等待这个列表被解析。

你必须使用 await 关键字来强制javascript等待,直到这一行被执行后再执行下一行。

const list = await this.usersmodel.find({ name: name }).exec()

此外,总括管道将整个订单文件带到收款处,因为在总括管道中没有对该订单进行过滤。

所以你必须在你的汇总管道中添加$match阶段,以便添加具有你指定的名称的订单列表。

又注意到我们需要 await 因为这是一个异步代码块,所以等到这个聚合完成后,再执行返回语句

所以整个函数应该是这样的

async order(name) {
    const list = await this.usersmodel.find({ name: name }).exec()
    //return list
    try {
        if(list){
            await this.usersmodel.aggregate([ // note the await here
                { $match: { name: name } }, // filtering the orders
                { $out: "payment" } // move them to the payment collection
            ])

            return "data saved in payment collection"
        }
    }
    catch (error) {
        return(error.message)
    }
}

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.