英文:
Mongoose setting Object IDs in updateMany
问题
I need to add IDs to many objects inside an array. Here's your code:
db.collection('collectionName').updateMany(
{ animals: { $ne: [] } },
{
$set: {
'animals.$[].cats.$[]._id': mongoose.Types.ObjectId(),
'animals.$[].dogs.$[]._id': mongoose.Types.ObjectId()
}
}
);
It's working, but the IDs are the same. To achieve unique IDs, you can generate a new unique ID for each object individually. Here's an updated code snippet:
db.collection('collectionName').updateMany(
{ animals: { $ne: [] } },
{
$set: {
'animals.$[].cats.$[]._id': { $each: [mongoose.Types.ObjectId()] },
'animals.$[].dogs.$[]._id': { $each: [mongoose.Types.ObjectId()] }
}
}
);
This code will generate a unique ID for each cat and dog object inside the arrays.
英文:
I need to add IDs to many object inside of array inside. Assume that my schema looks like this:
{
_id: something,
property:value,
animals: [
{
dogs: [
{ name: 'Dog1' },
{ name: 'Dog2' }
],
cats: [
{ name: 'Cat1' },
{ name: 'Cat2' }
]
}
]
}
I want to achieve something like this:
{
_id: something,
property:value,
animals: [
{
dogs: [
{ name: 'Dog1', _id: uniqueID },
{ name: 'Dog2', _id: uniqueID }
],
cats: [
{ name: 'Cat1', _id: uniqueID },
{ name: 'Cat2', _id: uniqueID }
]
}
]
}
My code
db.collection('collectionName').updateMany(
{ animals: { $ne: [] } },
{
$set: {
'animals.$[].cats.$[]._id': mongoose.Types.ObjectId(),
'animals.$[].dogs.$[]._id': mongoose.Types.ObjectId()
}
}
);
It works but IDs are exactly the same. How to achieve unique IDs?
答案1
得分: 1
这是因为 mongoose.Types.ObjectId()
是一个客户端函数。它在构建查询时执行,只有函数调用返回的值会包含在提交给服务器的请求中。
英文:
That happens because mongoose.Types.ObjectId()
is a client-side function. It is executed while building the query, and only the value returned by the function call is included in the request submitted to the server.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论