我想知道在Mongoose中更新文档之前检查文档中字段的最佳方法是什么。我知道我可以只使用public static SimpleAdapter constructTimezoneAdapter(Context context,
boolean sortedByName, int layoutId) {
final String[] from = new String[] {ZoneGetter.KEY_DISPLAYNAME, ZoneGetter.KEY_GMT};
final int[] to = new int[] {android.R.id.text1, android.R.id.text2};
final String sortKey = (sortedByName ? ZoneGetter.KEY_DISPLAYNAME : ZoneGetter.KEY_OFFSET);
final MyComparator comparator = new MyComparator(sortKey);
final List<Map<String, Object>> sortedList = ZoneGetter.getZonesList(context);
Collections.sort(sortedList, comparator);
final SimpleAdapter adapter = new SimpleAdapter(context,
sortedList,
layoutId,
from,
to);
return adapter;
}
,然后手动更新字段然后保存。但是,当您要发送带有要更新的多个字段的对象并且要更新的字段可能不同时,这很麻烦。因此,现在我要使用findOne()
进行查询,然后检查要检查的字段,然后使用findOne()
来更新文档。据我了解,updateOne()
不允许事先检查字段。那么这是最好的方法吗?向数据库发出2个请求似乎有点多余。在更新时打开查询是否还会有副作用?这是我使用的代码示例:
updateOne()
就像我说的那样,我在stackoverflow上找不到真正的好答案,猫鼬的文档似乎也无济于事。
答案 0 :(得分:1)
您可以使用findOneAndUpdate()。此方法:
查找匹配的文档,根据更新arg对其进行更新,传递任何选项,然后将找到的文档(如果有)返回给回调。
因此,在您的情况下,只需将条件添加到查询中,如果此方法找不到任何匹配项,则不会更新任何内容。
示例:
await Doc.findOneAndUpdate({ _id: req.body._id, method: {$ne: "foo"} }, req.body.bar);