【问题标题】:run time collections in express.jsexpress.js 中的运行时集合
【发布时间】:2015-11-26 21:07:00
【问题描述】:

我正在创建一个网络应用程序,用户可以在其中创建问题。每次用户创建问题时,都应创建一个集合,该问题的所有答案都应保存为该集合中的文档。

【问题讨论】:

  • 问题太宽泛,对 StackOverflow 不满意
  • 我是编码和 StackOverflow 的新手,请给我时间来提出更好的问题。

标签: node.js mongodb express


【解决方案1】:

您可以使用 mongodb ORM - mongoose 来制作这样的数据模型

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var questionSchema = Schema({
  title    : String,
  text     : String,
  user     : { type: Schema.Types.ObjectId, ref: 'User' },
  answers : [{ type: Schema.Types.ObjectId, ref: 'Answer' }]
});

var answerSchema = Schema({
  user : { type: Schema.Types.ObjectId, ref: 'User' },
  text    : String,
});

var Question  = mongoose.model('Question', questionSchema);
var Answer = mongoose.model('Answer', answerSchema);

因此,您将在问题中存储答案 ID 数组并可以填充数据:

Question.findOne().populate('answers').exec(function(err, doc){
  console.log(doc.answers) // here populated answers models
})

您还需要描述用户模型并使用附加数据问题和答案进行扩展

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2011-12-20
    • 2014-04-08
    相关资源
    最近更新 更多