gpt4 book ai didi

node.js - MongoDB。如何将文档从一个数组移动到另一个数组?

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:40 25 4
gpt4 key购买 nike

我有一个 session 集合。征集如下:

_id:ObjectId(5ce3c94f0e259e7370966c63)
status:Int32(1)
title:String(dfsb)
content:String(fdbfdbfd)
Array(visits):[
]
Array(visits_online):[
0:Object
start:Date(2019-05-22T08:06:50.222+00:00)
_id:ObjectId(5ce5031ae8ee2e83b9ab23ff)
session_id:ObjectId(5ce3c94f0e259e7370966c63)
user_id:ObjectId(5ce4f290e2971cc6791e5a11)
end:Date(2019-05-22T08:06:51.438+00:00)
1:Object
start:Date(2019-05-22T08:07:11.512+00:00)
_id:ObjectId(5ce5032fe8ee2e83b9ab2403)
session_id:ObjectId(5ce3c94f0e259e7370966c63)
user_id:ObjectId(5ce4f290e2971cc6791e5a11)
end:Date(2019-05-22T08:07:11.791+00:00)
]

我需要什么:我想从 visits_online 移动子文档数组到visits数组

_id:ObjectId(5ce3c94f0e259e7370966c63)
status:Int32(1)
title:String(dfsb)
content:String(fdbfdbfd)
Array(visits):[
0:Object
start:Date(2019-05-22T08:06:50.222+00:00)
_id:ObjectId(5ce5031ae8ee2e83b9ab23ff)
session_id:ObjectId(5ce3c94f0e259e7370966c63)
user_id:ObjectId(5ce4f290e2971cc6791e5a11)
end:Date(2019-05-22T08:06:51.438+00:00)
]
Array(visits_online):[
1:Object
start:Date(2019-05-22T08:07:11.512+00:00)
_id:ObjectId(5ce5032fe8ee2e83b9ab2403)
session_id:ObjectId(5ce3c94f0e259e7370966c63)
user_id:ObjectId(5ce4f290e2971cc6791e5a11)
end:Date(2019-05-22T08:07:11.791+00:00)
]

我尝试做的事情:

Session.update({ _id: '5ce3c94f0e259e7370966c63', 'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
{
$pull: { 'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
$push: { visits: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
})

如果有任何帮助,我将不胜感激。

最佳答案

您的 mongo 查询中有一个小错误,您需要告诉 mongo 从哪个数组中提取对象。

此外,您需要传递 ObjectId 而不是 string 来与更新查询中的 _id 进行匹配。

目前您将其传递为 _id : '5ce3c94f0e259e7370966c63' ,但应该是 _id : _id: mongoose.Types.ObjectId('5ce3c94f0e259e7370966c63')

试试这个:

Session.update({ 
_id: mongoose.Types.ObjectId('5ce3c94f0e259e7370966c63'),
'visits_online._id': mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff')
},{
$pull: { visits_online : { _id: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') }},
$push: { visits: mongoose.Types.ObjectId('5ce5031ae8ee2e83b9ab23ff') },
})

有关更多信息,请阅读 mongodb $pull documentation 。希望对您有所帮助!

关于node.js - MongoDB。如何将文档从一个数组移动到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56252255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com