草庐IT

javascript - Mongoose 只更新选定的字段或插入

coder 2023-11-05 原文

标题可能听起来像 findOne with $set 但不知何故我没有让它按照我想要的方式工作。

首先,我有一个 Ticket 模式

const Ticket = new Schema(Object.assign({
    ticketNumber: { type: String, required: true },
    year: { type: Schema.Types.Mixed, default: [] },  // object

}, BaseSchema), { timestamps: true });

然后我有一个函数可以将数据写入数据库。

我在下面的代码中也有一个模拟数据

exports.writeToDB = async () => {
    const data = [
        {
            ticketNumber: 123456789,
            year: 2019,
            notes: 'hello there',
            more: 'there should be more fields here'
        },
        {
            ticketNumber: 987654321,
            year: 2020,
            notes: 'hello there again',
            more: 'there should be more fields here again'
        }
    ];

    data.forEach(d => {
        console.log(d, 'ddd');
        const { ticketNumber, year, ...contents } = d;
        const query = { ticketNumber };
        const update = {
            'year': { [year]: contents }
        };
        const options = { upsert: true };
        Ticket.updateOne(query, update, options, (err, doc) => {
            console.log(doc, 'docc');
        })
    })
};

在架构中,只有 ticketNumberyear 一切都很好,但我想做的是,年份可能不同,ticketNumber 将保持不变。每次传入数据,如果找到ticketNumber则根据yearupdate,如果不是year然后找到插入

数据库中的示例是

{
    ticketNumber: 123456789,
    year: {
        2019: {
            notes: 'hello there',
            more: 'there should be more fields here'
        }
    }
};

如果传入的数据与 2019 相同,那么它将更新 notesmore 字段以及其他字段,但如果数据以不同的年份传入,例如 2020 那么 db 中的内容应该看起来像...

{
    ticketNumber: 123456789,
    year: [
        2019: {
            notes: 'hello there',
            more: 'there should be more fields here'
        },
        2020: {
            notes: 'hello there',
            more: 'there should be more fields here'
        },
    ]
};

我试图将我的 update 变量配置成这样

const update = {
    $set: {'year': { [year]: contents }}
};


const update = {
    'year': $set{ [year]: contents }
};

但是它们都不起作用,第一个会覆盖整个对象(符合预期)。第二个实际上什么都不做

关于我应该做什么的任何建议,或者我应该提供其他逻辑而不是使用像 $set 这样的东西?

在此先感谢您的帮助和建议。

最佳答案

我检查了 mongoose api,Model.update 方法在 documentation 中有这个注释:

所有不是原子操作名称的顶级键都被视为集合操作:

示例:

var query = { name: 'borne' };
Model.update(query, { name: 'jason bourne' }, options, callback);

// is sent as
Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
// if overwrite option is false. If overwrite is true, sent without the $set wrapper.

这意味着,在 mongoose 上使用 Model.update 时,您不必手动指定 $set,只需执行以下操作:

const update = {
    [`year.${year}`]: contents
};

关于javascript - Mongoose 只更新选定的字段或插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55836872/

有关javascript - 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 - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

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

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

  5. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

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

  7. ruby-on-rails - Sphinx - 何时对字段使用 'has' 和 'indexes' - 2

    我几天前在我的ruby​​onrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag

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

  9. Ruby - 如何处理子类意外覆盖父类(super class)私有(private)字段的问题? - 2

    假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案

  10. ruby-on-rails - 如何为空白字段编写 rspec? [Rails3.1] - 2

    我使用rails3.1+rspec和factorygirl。我对必填字段(validates_presence_of)的验证工作正常。我如何让测试将该事实用作“成功”而不是“失败”规范是:describe"Addanindustrywithnoname"docontext"Unabletocreatearecordwhenthenameisblank"dosubjectdoind=Factory.create(:industry_name_blank)endit{shouldbe_invalid}endend但是我失败了:Failures:1)Addanindustrywithnona

随机推荐