简体   繁体   English

猫鼬更新条件文件

[英]Mongoose update document with conditions

I need to unset mongo field which is ObjectId and refers to another schema if this ID is Id of a current user and this field is set. 我需要取消设置mongo字段,该字段是ObjectId,并且如果此ID是当前用户的ID并且已设置此字段,则引用另一个模式。 In other case, if this field is unset, current user ID should be set. 在其他情况下,如果未设置此字段,则应设置当前用户ID。 If the field is set and ObjectID doen't match the current user ID's mongo should return existing document but without changes apllied to the ObjectID field. 如果设置了该字段并且ObjectID不匹配,则当前用户ID的mongo应该返回现有文档,但不会对ObjectID字段进行任何更改。

Right now I find entry by ID and then check cases in my JS code. 现在,我按ID查找条目,然后在JS代码中检查大小写。 Then I perform another query in order to update the document. 然后,我执行另一个查询以更新文档。 But I think that this could be done by mongo in one query. 但是我认为这可以由mongo在一个查询中完成。

I'm using mongoose in my nodeJS 我在nodeJS中使用猫鼬

Mongoose findOneAndUpdate is the function you are looking for.It has following general syntax. Mongoose findOneAndUpdate是您要查找的函数。它具有以下常规语法。 query.findOneAndUpdate(conditions, update, options, callback) Edit: appended an example query. query.findOneAndUpdate(conditions, update, options, callback)编辑:附加了示例查询。

var query = {"_id": id};
var update = {name: {first: 'john', last: 'smith'}};
var options = {new: true};
People.findOneAndUpdate(query, update, options, function(err, person) {
  if (err) {
    console.log('got an error');
  }

  // at this point person is null.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM