0

I'm building sort of a question and answer system for my Meteor project. I have 3 collections: one named "Questions," one named "Answers," and one for admins to manually determine a question of the day, named "Today."

All collected answers will reference the question of the day. What I'm trying to figure out is how to make an insert statement for the "Answers" collection. Among the fields, it should add the ObjectId of the question being stored in "Today."

Answers.insert({
  user: Meteor.userId(), 
  date: new Date(),
  answer: answer,
  questions_id: **here is where I would like the ObjectId of the current question**
})

How can I reference and insert an ObjectId value, belonging to a field (let's call the field QOD) within the Today collection? If you have an answer with an actual example, it would be great. I'm not so experienced that someone can describe a solution to me without showing it. Thanks.

Of course, I'll also have to figure out how to publish this stuff later. But I'll cross that road when I get there.

Quin
  • 441
  • 5
  • 12

1 Answers1

1

If Answers needs to reference a record from Questions, then you need to obtain that record and include the _id field in the object you'll insert in Answers:

var question = Questions.findOne({...criteria...});
Answers.insert({
  user: Meteor.userId(),
  date: new Date(),
  answer: answer,
  questionId: question._id
});

Hope this helps. I see "Entries" instead of "Answers" in your question though so you may want to clarify. Also, instead of a separate "Today" collection, you may want to have a separate field in the Questions collection which would mark certain questions as being selected as "Question of the Day".

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • Thanks. I left "Entries" there by accident. It should be Answers. – Quin Feb 24 '14 at 05:31
  • Wait ... I think I got it. Thanks a million. – Quin Feb 24 '14 at 05:38
  • Welcome to StackOverflow! You can edit your own question and update `Entries` to `Answers`. As for what goes in the "criteria", that's a Mongo selector - see the [meteor docs for `find()`](http://docs.meteor.com/#find). To retrieve a single value, pass a `fields` key to `find`, then from the object returned by `findOne`, fetch the field you want (`_id` in my example above). [This post on Meteor collections](http://stackoverflow.com/questions/19826804/understanding-meteor-publish-subscribe/21853298#21853298) might help understand more about collections in general. – Dan Dascalescu Feb 24 '14 at 05:46
  • 1
    Ha, I figured criteria out and tried to edit that question really fast, but I guess you started answering quickly. It works perfectly. I can't upvote with my rep yet, but it's definitely accepted. – Quin Feb 24 '14 at 07:12
  • It looks like "questionId = question._id" should be "questionId: question._id." – Quin Feb 25 '14 at 23:43