草庐IT

javascript - 在 mongoDB 和 node js 中添加和更新子文档(没有 mongoose)

coder 2023-11-02 原文

我是 node js 和 mongoDB 的新手,我需要在 mongodb 集合上添加或更新子文档,如下所示:

{
    "_id": "58286e49769e3729e895d239",
    "id": "2",
    "title": "Session Title",
    "sessiondate": "2016-02-11T21:00:00.000Z",
    "startTime": "14:30",
    "endTime": "16:30",
    "breakStartTime": "16:30",
    "breakEndTime": "18:00",
    "talks": [
        {
            "id": "3",
            "title": "Android",
            "speaker": {
                "id": "1",
                "name": "john doe",
                "about": "about the speaker",
                "photo": "https://pbs.twimg.com/profile_images/566353055788978177/dUy_ueY2.jpeg"
            }
        }
    ]
}

我找到的所有解决方案都使用 Mongoose ,在这个特定项目中我们决定不使用 Mongoose ,有什么想法吗?

最佳答案

要在嵌入文档中添加或更新新的talk,您可以使用任何原子update operators取决于集合中有多少文档 你想更新。对于单个原子更新,请使用 updateOne() 方法如下例所示:

<强>1。添加新的子文档

// Example of adding a subdocument to an existing document.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // The new talk document to be added 
    var doc = {
        "id": "4",
        "title": "PyData",
        "speaker": {
            "id": "7",
            "name": "alice bob",
            "about": "about the speaker",
            "photo": "https://pbs.twimg.com/dUy_ueY2.jpeg"
        }
    };

    // Update the document with an atomic operator
    collection.updateOne(
        { "_id": ObjectId("58286e49769e3729e895d239") },
        { "$push": { "talks": doc } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

在上面,您使用 $push 运算符将指定文档附加到嵌入文档数组(talks 字段)。


<强>2。更新现有的子文档

// Example of updating an existing subdocument.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // Update the document with an atomic operator
    collection.updateOne(
        { 
            "_id": ObjectId("58286e49769e3729e895d239"),
            "talk.id": "3"
        },
        { "$set": { 
            "talks.$.title": "Android version 7.0",
            "talks.$.speaker.name": "foo bar"
        } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

对于现有文档更新,您应用 $set运算符连同 $ positional operator在您的更新操作中更改嵌入的文档字段。 $ positional operator将识别数组中要更新的正确元素,而无需明确指定元素在数组中的位置。为此,数组字段必须作为查询文档的一部分出现,因此查询

{ 
    "_id": ObjectId("58286e49769e3729e895d239"),
    "talk.id": "3" // <-- array field is part of the query
}

关于javascript - 在 mongoDB 和 node js 中添加和更新子文档(没有 mongoose),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40759320/

有关javascript - 在 mongoDB 和 node js 中添加和更新子文档(没有 mongoose)的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. 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

  3. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  4. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  5. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

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

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

  9. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  10. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

随机推荐