问题
I am working on nestjs and I have two collections one is order and the second is payment. Now I need to retrieve one document from the collection order and save it into payment collection which is working properly but the issue is when I am trying to save the second document into payment collection then my first document is overwritten. In other words, the first document has vanished after submitting the second document. I want to save every document in payment collection which i retrieved from orders document.
Here is the code of service:
async order(name){
const list=await this.usersmodel.find({name:name}).exec()
//return list
try{
if(list){
const x=await this.usersmodel.aggregate([
{ $match: { name: name } },
{$out:"payment"}
])
return "data saved in payment collection"
}
}
catch(error){
return(error.message)
}
}
code of controller-:
@Post('orderdata')
async orderdata(@Body('name')name){
return this.usersService.order(name)
}
回答1:
according to the docs, $out
is replacing the whole collection if it exists, with the one you provided, so when you do it, it will replace the old one
if your mongodb
version is > 4.2, you can use $merge
instead,
in $merge
, it adds the new document to the collection if it exists, also you can define the behavior if the new document already exists (keep the old one, or overwrite it) and if it does not exist (insert or ignore it)
you can see all of that in the documentation of $merge here
also you can find a comparison between $out and $merge here
in your code, it should be something like
async order(name) {
const list = await this.usersmodel.find({ name: name }).exec()
//return list
try {
if(list) {
const x = await this.usersmodel.aggregate([
{ $match: { name: name } },
{ $merge: { into: "payment" } } // you can define other options here like if the document already exists, keep the old one or not and so on, all of that you can find in the documentation
])
return "data saved in payment collection"
}
}
catch(error){
return(error.message)
}
}
hope it helps
来源:https://stackoverflow.com/questions/61700144/how-to-transfer-multiple-data-from-one-collection-to-another-using-out-aggregat