What I need to do is… store _id
in the different document in different collection right after a document is inserted.
For example, I have a button to create or edit todos. Each todo has _id
, title
and description
. So after hitting the save button, users can create a new todo or update an existing todo.
And I’m focusing on creating
a new todo here.
client side
const Todos = ({ listId }) => {
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const listId = '12312313'
const handleUpdate = ({title, description}) => {
Meteor.call("updateTodo", _id, title, description, listId);
};
return (
<>
.
.
.
<button onClick={handleUpdate}>Update or create todo</button>
</>
);
};
server side
Meteor.methods({
updateTodo(_id = "", title, description, listId) {
check(_id, Match.Maybe(String));
check(title, String);
check(description, String);
check(listId, String);
Todos.update(
{ _id },
{
$set: {
title: title,
description: description,
}
},
{ upsert: true, multi: false }
);
}
});
I like to store _id
that’s not existing in Todos
collection yet in one of the documents in Lists
collection when the save button is clicked.
So the flow will be
1, Users click the save button to create a new todo
2, updateTodo
gets called
3, Title, description are stored in a new document (mongodb automatically generates _id
)
4, _id
needs to be stored in todoIds
property that’s in Lists
collection (I have access to listsId
so I can get an document from Lists
collection that I need to store this _id
)
I do not know how to access _id
in Todos
collection and also don’t know how to store it in the document in Lists
collection.
Attempts
I simply added this code below after Todos.update()
Lists.direct.update(listId, {$set: {todoIds: [_id]}});
I checked if the document in Lists
collection is updated but todoIds
property is set to [null]
. what I want to store is _id
from the document in Todos
collection.
additional question
Right now if Lists.direct.update(listId, {$set: {todoIds: [_id]}});
works, the todoIds
property will be overwritten by _id
.
But what I want to do here is add _id
to the end of the todoIds
array so the document would look like this.
{
_id:'1231231',
todoIds : [
'asdasssdasd',
'dfgthfghfhf',
'slirfjlsffs' // that's _id from the document in Todos collection
]
}
Thanks in advance.