【问题标题】:Set or create embedded document in Mongoose在 Mongoose 中设置或创建嵌入文档
【发布时间】:2014-07-13 05:03:03
【问题描述】:

我有一个架构如下:

/**
 * Answer Schema
 */
var AnswerSchema = new Schema({
  answer: Number,
  owner_id: Schema.Types.ObjectId
});

/**
 * Poll Schema
 */
var PollSchema = new Schema({
  question: { type: String, required: true, trim: true },
  choices: [ { type: String, required: true, trim: true} ],
  answers: [AnswerSchema]
});

如何为给定的 poll_id 和回答投票的人的 owner_id 设置答案?

【问题讨论】:

    标签: mongodb mongoose database


    【解决方案1】:

    “设置或创建”这个术语有点打开了这一点。

    基本上,您将使用$push 运算符和.update() 在数组中添加(创建)新项目,或者在@987654326 之后拥有当前文档后使用标准JavaScript 数组推送@。

    但考虑到您可能想要“更新”给定所有者的现有答案,那么这可能是一个两步操作。如果没有,那么您只需要使用$push 进行“更新”。

    PollSchema.update(
        { "_id": poll_id, "answers.owner_id": owner_id }
        { "$set":{ "answers.answer": value } },
        function(err,numAffected) {
    
           if (err)
              throw err;        // or whatever handling
    
           // If this didn't modify anything then $push a document
           if ( numAffected != 0 ) {
               PollSchema.update(
                   { "_id": poll_id },
                   { "$push": { 
                       "answers": { 
                           "owner_id": owner_id,
                           "answer": value
                       }
                   }},
                   function(err, numAffected) {
                      // more things in here
                   }
               );
    
        }
    );
    

    或者,如果您不关心每个“所有者”有多个答案,那么只需使用 $push 更新即可。

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 2013-06-29
      • 2014-08-08
      • 2018-03-30
      • 1970-01-01
      • 2013-03-07
      • 2015-07-17
      • 2012-02-18
      相关资源
      最近更新 更多