标题可能听起来像 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');
})
})
};
在架构中,只有 ticketNumber 和 year
一切都很好,但我想做的是,年份可能不同,ticketNumber 将保持不变。每次传入数据,如果找到ticketNumber则根据yearupdate,如果不是year然后找到插入。
数据库中的示例是
{
ticketNumber: 123456789,
year: {
2019: {
notes: 'hello there',
more: 'there should be more fields here'
}
}
};
如果传入的数据与 2019 相同,那么它将更新 notes 和 more 字段以及其他字段,但如果数据以不同的年份传入,例如 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/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数
我知道我可以指定某些字段来使用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
我正在尝试为我的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
我几天前在我的rubyonrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag
这太简单了,太荒谬了,我在任何地方都找不到关于它的任何信息,包括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
假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案
我使用rails3.1+rspec和factorygirl。我对必填字段(validates_presence_of)的验证工作正常。我如何让测试将该事实用作“成功”而不是“失败”规范是:describe"Addanindustrywithnoname"docontext"Unabletocreatearecordwhenthenameisblank"dosubjectdoind=Factory.create(:industry_name_blank)endit{shouldbe_invalid}endend但是我失败了:Failures:1)Addanindustrywithnona