I have the following schema:
...
friends: {
type: Map,
of: String
},
...
I am creating a game where you can add friends, so I want to store friend's username and ID in that map. When I do
const requestantFriends = await UserData.findOne({userId: requestantData._id})
await UserData.findOneAndUpdate({userId: requestantData._id}, {friends: requestantFriends.friends.set(targetData._id, "test")}, {new: true})
nothing seems to happen. If I check the database, it still says Map(0) {} . How can I update a document's map and save it?
I've also tried
const requestantFriends = await UserData.findOne({userId: requestantData._id})
await requestantFriends.friends.set(targetData._id, "test")
await requestantFriends.save()
I'm assuming the 'friends' map is a field in the UserData model.
Here's the code!
await UserData.findOneAndUpdate({userId: requestantData._id}, {
$set: {
[`friends.${targetData._id}`]: "test",
}
});
First, we find the document whose userId
matches requestantDate._id
. Then, we use the MongoDB $set
operator to add a new key-value pair. We wrap the key in brackets to indicate that its value incorporates a variable, and then we use backticks to create a template literal so that we can insert the variable key name. Finally, we provide a value and close everything out!
MongoDB stores data using BSON , which does not have a Map
type.
When Mongoose saves a document containing a map, it is stored in MongoDB as an embedded object.
If you retrieve the object using find
, Mongoose will reconstitute the object as a map, and you would then need to use get
and set
to modify the contents.
When using findOneAndUpdate
, or any of the update
variants, Mongoose sends the operation to MongoDB for it to perform on the server side.
The operation that MongoDB would understand is $set
, so the update should look like:
await UserData.findOneAndUpdate({userId: requestantData._id}, {$set: {"friends._id": "test"})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.