草庐IT

Node.js Mongoose 更新嵌入式文档,拉动不持久

coder 2023-11-02 原文

我正在使用 Mongoose 3.4.0 和 MongoDB 2.0.6。

我有以下架构:

var Database = module.exports = function Database(){};

Database.prototype = {

  _model : {},
  _schema: {
     Comment : new Schema ({
  _id : ObjectId,
  comment : { type : String },
  date : { type : Date, default : Date.now },
  userId : { type : Schema.ObjectId, ref : 'User' },
  nickname : { type : String },
  profileLinkAn : { type : String },
  profileLinkIos : { type : String }
}),

Game : new Schema ({
  roomName : { type : String },
  openTime : { type : Date },
  closeTime : { type : Date, index : true },
  minPlayers : { type : Number },
  maxPlayers : { type : Number},
  numberOfPlayers : { type : Number, default : 0 },
  winner : { userId : { type : Schema.ObjectId, ref : 'User'} },
  runrUp : { userId : { type : Schema.ObjectId, ref : 'User' } },
  semiFn : [ { type : Schema.ObjectId, ref : 'User'} ],
  qtrFn : [ { type : Schema.ObjectId, ref : 'User' } ],
  rnd16 : [ { type : Schema.ObjectId, ref : 'User' } ],
  rnd32 : [ { type : Schema.ObjectId, ref : 'User' } ],
  prize : [ this.Prize ],
  tag : [ { type : String, index : true } ],
  status : { type : Number, index : true },
  businessType : { type : Number },
  mallId : { type : Schema.ObjectId, ref : 'Mall', index : true },
  registeredPlayers : [ { type : ObjectId, ref : 'User' } ],
  thumbnailImage : [ this.PrizeDetailImage ],
  gamePrice : { type : Number },
  slotPrice : { type : Number },
  comment : [ this.Comment ],
  commentCnt : { type : Number, default : 0 },
  wantUid : [ { type : Schema.ObjectId, ref : 'User' } ],
  wantCnt : { type : Number, default : 0 }
    })
 },

 connect : function(url) {

    mongoose.connect(url);
    this._model.Comment = mongoose.model('Comment',this._schema.Comment);

    this._model.Game = mongoose.model('Game', this._schema.Game);
},

model : function(model) {
    switch (model) {
        case 'Comment':
            return this._model.Comment;
        case 'Game':
            return this._model.Game;
    }
}

}

以上内容来自 Database.js。以下是我的 express 应用程序中的代码。为了简洁起见,我省略了一些代码。我的问题似乎与查询有关。

var Game = this.db.model('Game');
Game.update({ _id : req.body._id }, { $pull : { comment : { _id : req.body.commentId } }               }, function (err,numAffected,raw) {
if(err)
{
      res.json({ data : { success : false } });
}
else
{
    console.log(raw);
    res.json({ data : { success : true } });
}
});

我没有收到任何错误消息,Mongo 的原始输出是:

{ updatedExisting: true,
  n: 1,
  connectionId: 78912,
  err: null,
  ok: 1 }

但是当我查看我收藏的内容时,子文档仍然存在。我曾尝试使用 native 驱动程序但没有成功。我在我的架构中做错了什么吗?在此先感谢您抽出宝贵时间查看此内容。

/肯利

最佳答案

好的,Victor 在 mongoose google 组中向我指出了这一点,因此对他表示敬意。事实证明, Mongoose 并未自动将 ObjectId 转换为 ObjectId。这是查询现在的样子:

Game.update({ _id : req.body._id }, { $pull : { comment :  { _id : this.db.objectId(req.body.commentId) } } }, function (err,numAffected,raw) {
                if(err)
                {
                    console.log(err);
                    res.json({ data : { success : false } });
                }
                else
                {
                    console.log(raw);
                    res.json({ data : { success : true } });
                }
            });

如果有人想知道我将它添加到我的数据库原型(prototype)中以便我可以在任何地方访问 ObjectId 类型。

Database.prototype = {

objectId : mongoose.Types.ObjectId,
}

希望这可以帮助其他遇到类似问题的人。

关于Node.js Mongoose 更新嵌入式文档,拉动不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13682017/

有关Node.js Mongoose 更新嵌入式文档,拉动不持久的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  3. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  4. Matlab imread()读到了什么 (浅显 当复习文档了) - 2

    matlab打开matlab,用最简单的imread方法读取一个图像clcclearimg_h=imread('hua.jpg');返回一个数组(矩阵),往往是a*b*cunit8类型解释一下这个三维数组的意思,行数、数和层数,unit8:指数据类型,无符号八位整形,可理解为0~2^8的数三个层数分别代表RGB三个通道图像rgb最常用的是24-位实现方法,即RGB每个通道有256色阶(2^8)。基于这样的24-位RGB模型的色彩空间可以表现256×256×256≈1670万色当imshow传入了一个二维数组,它将以灰度方式绘制;可以把图像拆分为rgb三层,可以以灰度的方式观察它figure(1

  5. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  6. ruby-on-rails - Rails Associations 的更新方法是什么? - 2

    这太简单了,太荒谬了,我在任何地方都找不到关于它的任何信息,包括API文档和Rails源代码:我有一个:belongs_to关联,我开始理解当您没有关联时您在Controller中调用的正常模型方法与您有关联时调用的方法略有不同。例如,我的关联在创建Controller操作时运行良好:@user=current_user@building=Building.new(params[:building])respond_todo|format|if@user.buildings.create(params[:building])#etcetera但我找不到关于更新如何工作的文档:@user

  7. Ruby 等同于 Sphinx 文档生成器? - 2

    Ruby有一些不错的文档生成器,例如Yard、rDoc,甚至Glyph。问题是Sphinx可以做网站、PDF、epub、LaTex等。它在重组文本中完成所有这些事情。在Ruby世界中有替​​代方案吗?也许是程序的组合?如果我也能使用Markdown就更好了。 最佳答案 自1.0版以来,Sphinx有了“域”的概念,它是从Python和/或C以外的语言标记代码实体(如方法调用、对象、函数等)的方法。有一个rubydomain,所以你可以只使用Sphinx本身。您唯一会缺少的(我认为)是Sphinx使用autodoc从源代码自动创建文档

  8. ruby-on-rails - OSX Yosemite 更新破坏了 pow.cx - 2

    升级到OSXYosemite后,我现有的pow.cx安装不起作用。升级到最新的pow.cx无效。通过事件监视器重新启动它也没有成功。 最佳答案 卸载(!)并重新安装解决了这个问题。curlget.pow.cx/uninstall.sh|shcurlget.pow.cx|sh 关于ruby-on-rails-OSXYosemite更新破坏了pow.cx,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/q

  9. ruby - 将 Gitlab 从 9.3.7 更新到 9.3.8 安装 re2 时出错 - 2

    我们在Ubuntu14.04和Gitlab9.3.7上运行,运行良好。我们正在尝试更新到Gitlabv9.3.8的最新安全补丁,但它给我们这个错误:Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension.currentdirectory:/home/git/gitlab/vendor/bundle/ruby/2.3.0/gems/re2-1.0.0/ext/re2/usr/local/bin/ruby-r./siteconf20170720-19622-15i0edf.rbextconf.rbcheckingformain(

  10. ruby-on-rails - Rails 更新属性 - 2

    我遇到了以下问题。我有一个名为user的模型,它有一个名为activated的列。我试图通过激活的方法更新该值?但它给我错误:验证失败:密码不能为空,密码太短(最少6个字符)这对我来说没有意义,因为我没有接触密码字段!我只想更新激活的列。我把我认为相关的代码放在这里,但如果你认为你需要更多,请问:)非常感谢您!型号:attr_accessor:passwordattr_accessible:name,:email,:password,:password_confirmation,:activatedhas_many:sucu_votesemail_regex=/\A[\w+\-.]+@

随机推荐