如果您想了解MongoosefindByIdAndUpdateupsert在初始插入时返回空文档的相关知识,那么本文是一篇不可错过的文章,我们将对mongoosefind报错进行全面详尽的解释,并且为
如果您想了解Mongoose findByIdAndUpdate upsert在初始插入时返回空文档的相关知识,那么本文是一篇不可错过的文章,我们将对mongoose find报错进行全面详尽的解释,并且为您提供关于Apollo graphql 和 Mongoose findOneUpdate 文档、com.mongodb.client.model.FindOneAndUpdateOptions的实例源码、findByIdAndRemove无法在Mongoose中同时删除多个文档、findOneAndUpdate 在 mongodb 中不起作用的有价值的信息。
本文目录一览:- Mongoose findByIdAndUpdate upsert在初始插入时返回空文档(mongoose find报错)
- Apollo graphql 和 Mongoose findOneUpdate 文档
- com.mongodb.client.model.FindOneAndUpdateOptions的实例源码
- findByIdAndRemove无法在Mongoose中同时删除多个文档
- findOneAndUpdate 在 mongodb 中不起作用
Mongoose findByIdAndUpdate upsert在初始插入时返回空文档(mongoose find报错)
这个基本的Mongoose模型代码在初始调用时返回空结果(gameMgr),但在后续调用中起作用。它不应该在初始upsert中返回填充的结果对象吗?mongo记录存在,并且在相同情况下第二次运行代码,因为没有插入,所以一切正常。
如果预期结果对象为空,那么创建新对象的合适模式是什么?(或者我是否会重新加载 另一个 数据库调用并进一步陷入回调疯狂状态?)
GameManagerModel.findByIdAndUpdate( game._id, {$setOnInsert: {user_requests:[]}}, {upsert: true}, function(err, gameMgr) { console.log( gameMgr ); // NULL on first pass, crashes node gameMgr.addUserRequest( newRequest ); });
答案1
小编典典在Mongoose
4.0中,(和)new
选项的默认值已更改为(请参阅发行说明)。这意味着您需要显式设置选项以获取由upsert创建的文档:findByIdAndUpdate``findOneAndUpdate``false
true
GameManagerModel.findByIdAndUpdate( game._id, {$setOnInsert: {user_requests:[]}}, {upsert: true, new: true}, function(err, gameMgr) { console.log( gameMgr ); gameMgr.addUserRequest( newRequest ); });
Apollo graphql 和 Mongoose findOneUpdate 文档
如何解决Apollo graphql 和 Mongoose findOneUpdate 文档?
我有一个项目,我使用 apollo graphql 和 mongoose 自从我尝试使用我的 findOneUpdate 修改用户以来已经有一段时间了 但问题是它根本没有发生,它没有给我任何错误,如果我返回文档修改它给我一个文档
这是我的架构
const userSchema = new Schema({
firstname : {type: String},lastname: {type: String},phoneNumber: {type: String},username: {type: String},email: {type: String},password: {type: String},address: {type: String},status: {type : String,enum: [''disABLED'',''ACTIVED''],default: "ACTIVED" },state : { type: String,enum:[''PAYED'',''NOT_PAYED'']},tokenForSetting: {type: String},role: {type : String,enum: [''SUPER_ADMIN'',''ADMIN'',''SECRETAIRE'',''MEDECIN'',''PATIENT'']},description: {type: String},specialite: {type: String},Structure: {type: Schema.Types.ObjectId,ref : ''Structure''},nationality: {type: String},indicatif: {type: String},country: {type: String},homeworking: {type: String},email_home_working: {type: String},phone_home_working: {type: String},subscriptions: [
{
subscription: { type: String},date_start: { type: Date},date_end:{ type: Date},status: { type : String,enum: [''ACTIVATE'',''DESACTIVATE'',''EXPIRED'']}
}
],photo: {type: String},isDeleted: {type: Boolean},assurance: { type: Schema.Types.ObjectId,ref : ''Assurance''},assurance_tpc: {type: Number},},{timestamps: true});
我的类型定义
type User {
id: ID!
firstname: String
lastname: String
phoneNumber: String
email: String
username: String
password: String
address: String
status: String
state: String
tokenForSetting: Token
role: String
description: String
specialite: String
Structure: String
nationality: String
indicatif: String
country: String
homeworking: String
email_home_working:String
phone_home_working: String
subscriptions: Subscription
photo: String
isDeleted:Boolean
assurance: Assurance
assurance_tpc: number,}
变异
updateUser(id: String,data: UserInput): User
函数变异
updateUser: async(parent: any,args: any,context: any,info: any) => {
try {
let all_data = JSON.parse(JSON.stringify(args));
let toUpdate = all_data[''data''];
let id = all_data.id;
if(toUpdate.password){
toUpdate.password = bcrypt.hashSync(toUpdate.password,saltRounds);
}
if(toUpdate.phoneNumber) {
// Verifier si Un user avec ce meme numéro existe deja
const isExist = await Utils.isExsit(id,toUpdate.phoneNumbre);
if(isExist == true) {
throw new Error("A user has already registered with this phone number");
}
}
await User.findOneAndUpdate({
_id: id
},{toUpdate},{ upsert: true },(err: any,doc: any) => {
console.log(doc);
if(!err) {
if(doc == null) {
return "Error: can not do this ";
}
else {
return doc;
}
}else {
//return err
throw new Error("Error: this user can not update");
}
});
// return response;
}
catch (error) {
throw new Error(error);
}
}
如果你能帮助我,因为我在这里没有看到错误
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
com.mongodb.client.model.FindOneAndUpdateOptions的实例源码
public O2MSyncDataLoader getPendingDataLoader() { O2MSyncDataLoader loader = null; Document document = syncEventDoc.findOneAndUpdate( Filters.and(Filters.eq(SyncAttrs.STATUS,SyncStatus.PENDING),Filters.eq(SyncAttrs.EVENT_TYPE,String.valueOf(EventType.System))),Updates.set(SyncAttrs.STATUS,SyncStatus.IN_PROGRESS),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER) .projection(Projections.include(SyncAttrs.soURCE_DB_NAME,SyncAttrs.soURCE_USER_NAME))); if (document != null && !document.isEmpty()) { Object interval = document.get(SyncAttrs.INTERVAL); String appName = document.getString(SyncAttrs.APPLICATION_NAME); if(interval!=null && interval instanceof Long){ loader = new O2MSyncDataLoader((Long)interval,appName); }else{ loader = new O2MSyncDataLoader(120000,appName); } loader.setEventId(document.getobjectId(SyncAttrs.ID)); loader.setdbname(document.getString(SyncAttrs.soURCE_DB_NAME)); loader.setDbUserName(document.getString(SyncAttrs.soURCE_USER_NAME)); loader.setStatus(document.getString(SyncAttrs.STATUS)); } return loader; }
protected final FluentFuture<Optional<T>> doModify( final Constraints.ConstraintHost criteria,final Constraints.Constraint update,final FindOneAndUpdateOptions options) { checkNotNull(criteria,"criteria"); checkNotNull(update,"update"); return submit(new Callable<Optional<T>>() { @Override public Optional<T> call() throws Exception { @Nullable T result = collection().findOneAndUpdate( convertToBson(criteria),convertToBson(update),options); return Optional.fromNullable(result); } }); }
protected final FluentFuture<Integer> doUpdateFirst( final Constraints.ConstraintHost criteria,final FindOneAndUpdateOptions options ) { checkNotNull(criteria,"update"); checkNotNull(options,"options"); return submit(new Callable<Integer>() { @Override public Integer call() { T result = collection().findOneAndUpdate( convertToBson(criteria),options); return result == null ? 0 : 1; } }); }
@Override public Optional<T> peek() { final Bson peekQuery = QueryUtil.generatePeekQuery(defaultHeartbeatExpirationMillis); final Document update = new Document(); update.put("heartbeat",new Date()); update.put("status",OkraStatus.PROCESSING.name()); final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.AFTER); final Document document = client .getDatabase(getDatabase()) .getCollection(getCollection()) .findOneAndUpdate(peekQuery,new Document("$set",update),options); if (document == null) { return Optional.empty(); } return Optional.ofNullable(serializer.fromDocument(scheduleItemClass,document)); }
@Test public void updatePojotest() { Bson update = combine(set("user","Jim"),set("action",Action.DELETE),// unfortunately at this point we need to provide a non generic class,so the codec is able to determine all types // remember: type erasure makes it impossible to retrieve type argument values at runtime // @todo provide a mechanism to generate non-generic class on the fly. Is that even possible ? // set("listofpolymorphicTypes",buildNonGenericclassOnTheFly(Arrays.asList(new A(123),new B(456f)),List.class,Type.class),set("listofpolymorphicTypes",new polymorphicTypeList(Arrays.asList(new A(123),new B(456f)))),currentDate("creationDate"),currentTimestamp("_id")); FindOneAndUpdateOptions findOptions = new FindOneAndUpdateOptions(); findOptions.upsert(true); findOptions.returnDocument(ReturnDocument.AFTER); MongoCollection<Pojo> pojoMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Pojo.class); Pojo pojo = pojoMongoCollection.findOneAndUpdate(Filters.and(Filters.lt(DBCollection.ID_FIELD_NAME,0),Filters.gt(DBCollection.ID_FIELD_NAME,0)),update,findOptions); assertNotNull(pojo.id); }
@Override public TDocument findOneAndUpdate(Bson filter,Bson arg1,FindOneAndUpdateOptions arg2) { OperationMetric metric = null; if (MonGologger.GATHERER.isEnabled()) { List<String> keyvaluePairs = MongoUtilities.getkeyvaluePairs(filter); keyvaluePairs.add("update"); keyvaluePairs.add(CacheUtilities.safetoString(arg1)); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : findOneAndUpdate " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName,keyvaluePairs); if (MonGologger.isRequestSizeMeasured()) { metric.setProperty(CommonMetricProperties.REQUEST_SIZE_BYTES,Integer.toString(measureDocumentSize(arg1))); } addWriteConcern(metric); addReadConcernAndPreference(metric); } TDocument retVal = collection.findOneAndUpdate(filter,arg1,arg2); stopMetric(metric,measureDocumentSizeIfResultSizeEnabled(retVal)); return retVal; }
@Override public Long getNextIdGen(Long interval) { Document realUpdate = getIncUpdateObject(getUpdateObject(interval)); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .upsert(true) .returnDocument(ReturnDocument.AFTER); Document ret = getIdGenCollection().findOneAndUpdate(getQueryObject(),realUpdate,options); if (ret == null) return null; Boolean valid = (Boolean) ret.get(VALID); if (valid != null && !valid) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,mongoMsgCatalog.getMessage("IdGenerator")); } return (Long) ret.get(SEQ); }
@Override public void updateRow(String rowId,Map<String,Object> recordValues) { String key = getKey(rowId); // stupid key is row id plus "l/" prepended // to it MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName,tableName); Document query = new Document(); query.put(KEY,key); Document toPut = new Document(); toPut.put(KEY,key); toPut.put(ROWID,rowId); toPut.put(EPOCH,EpochManager.nextEpoch(collection)); toPut.putAll(recordValues); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER); @SuppressWarnings("unused") Document ret = collection.findOneAndUpdate(query,new Document($SET,toPut),options); }
@Override public boolean insertRecord(LockConfiguration lockConfiguration) { Bson update = combine( setonInsert(LOCK_UNTIL,Date.from(lockConfiguration.getLockAtMostUntil())),setonInsert(LOCKED_AT,Now()),setonInsert(LOCKED_BY,hostname) ); try { Document result = getCollection().findOneAndUpdate( eq(ID,lockConfiguration.getName()),new FindOneAndUpdateOptions().upsert(true) ); return result == null; } catch (MongoCommandException e) { if (e.getErrorCode() == 11000) { // duplicate key // this should not normally happen,but it happened once in tests return false; } else { throw e; } } }
@ExtDirectMethod(ExtDirectMethodType.FORM_POST) public ExtDirectFormPostResult resetRequest( @RequestParam("email") String emailOrLoginName) { String token = UUID.randomUUID().toString(); User user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.and( Filters.or(Filters.eq(CUser.email,emailOrLoginName),Filters.eq(CUser.loginName,emailOrLoginName)),Filters.eq(CUser.deleted,false)),Updates.combine( Updates.set(CUser.passwordResetTokenValidUntil,Date.from(zoneddatetime.Now(ZoneOffset.UTC).plusHours(4) .toInstant())),Updates.set(CUser.passwordResetToken,token)),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER) .upsert(false)); if (user != null) { this.mailService.sendPasswortResetEmail(user); } return new ExtDirectFormPostResult(); }
/** * Saves a set of {@link ProtectedRegion} for the specified world to database. * * @param world The name of the world * @param set The {@link Set} of regions * @throws StorageException Thrown if something goes wrong during database query */ public void saveAll(final String world,Set<ProtectedRegion> set) throws StorageException { MongoCollection<ProcessingProtectedRegion> collection = getCollection(); final atomicreference<Throwable> lastError = new atomicreference<>(); final CountDownLatch waiter = new CountDownLatch(set.size()); for (final ProtectedRegion region : set) { if (listener != null) listener.beforeDatabaseUpdate(world,region); collection.findOneAndUpdate( Filters.and(Filters.eq("name",region.getId()),Filters.eq("world",world)),new ProcessingProtectedRegion(region,new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER),OperationResultCallback.create(lastError,waiter,new UpdateCallback(world)) ); } ConcurrentUtils.safeAwait(waiter); Throwable realLastError = lastError.get(); if (realLastError != null) throw new StorageException("An error occurred while saving or updating in MongoDB.",realLastError); }
@Override public io.vertx.ext.mongo.MongoClient findOneAndUpdateWithOptions(String collection,JsonObject query,JsonObject update,FindOptions findOptions,UpdateOptions updateOptions,Handler<AsyncResult<JsonObject>> resultHandler) { requireNonNull(collection,"collection cannot be null"); requireNonNull(query,"query cannot be null"); requireNonNull(update,"update cannot be null"); requireNonNull(findOptions,"find options cannot be null"); requireNonNull(updateOptions,"update options cannot be null"); requireNonNull(resultHandler,"resultHandler cannot be null"); JsonObject encodedQuery = encodeKeyWhenUSEObjectId(query); Bson bquery = wrap(encodedQuery); Bson bupdate = wrap(update); FindOneAndUpdateOptions foauOptions = new FindOneAndUpdateOptions(); foauOptions.sort(wrap(findOptions.getSort())); foauOptions.projection(wrap(findOptions.getFields())); foauOptions.upsert(updateOptions.isUpsert()); foauOptions.returnDocument(updateOptions.isReturningNewDocument() ? ReturnDocument.AFTER : ReturnDocument.BEFORE); MongoCollection<JsonObject> coll = getCollection(collection); coll.findOneAndUpdate(bquery,bupdate,foauOptions,wrapCallback(resultHandler)); return this; }
protected final FluentFuture<Optional<T>> doModify( final Constraints.ConstraintHost criteria,options); return Optional.fromNullable(result); } }); }
protected final FluentFuture<Integer> doUpdateFirst( final Constraints.ConstraintHost criteria,options); return result == null ? 0 : 1; } }); }
@Override public Optional<T> reschedule(final T item) { validateReschedule(item); final Document query = new Document(); query.put("_id",new ObjectId(item.getId())); query.put("heartbeat",DateUtil.toDate(item.getHeartbeat())); final Document setDoc = new Document(); setDoc.put("heartbeat",null); setDoc.put("runDate",DateUtil.toDate(item.getRunDate())); setDoc.put("status",OkraStatus.PENDING.name()); final Document update = new Document(); update.put("$set",setDoc); final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.AFTER); final Document document = client .getDatabase(getDatabase()) .getCollection(getCollection()) .findOneAndUpdate(query,document)); }
@Override public Optional<T> heartbeatandUpdateCustomAttrs(final T item,final Map<String,Object> attrs) { validateHeartbeat(item); final Document query = new Document(); query.put("_id",new ObjectId(item.getId())); query.put("status",OkraStatus.PROCESSING.name()); query.put("heartbeat",DateUtil.toDate(item.getHeartbeat())); final Document update = new Document(); update.put("$set",new Document("heartbeat",new Date())); if (attrs != null && !attrs.isEmpty()) { attrs.forEach((key,value) -> update.append("$set",new Document(key,value))); } final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.AFTER); final Document result = client .getDatabase(getDatabase()) .getCollection(getCollection()) .findOneAndUpdate(query,options); if (result == null) { return Optional.empty(); } return Optional.ofNullable(serializer.fromDocument(scheduleItemClass,result)); }
public SyncEvent getPendingEvent(List<String> eventTypes) { return syncEvents.findOneAndUpdate( Filters.and(Filters.eq(SyncAttrs.STATUS,Filters.in(SyncAttrs.EVENT_TYPE,eventTypes)),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public SyncNode getFailedNode(long lastPingTime) { SyncNode FailedNode = syncNodeMapping.findOneAndUpdate( Filters.and(Filters.lte(SyncAttrs.LAST_PING_TIME,lastPingTime),Filters.eq(SyncAttrs.LIFE_CYCLE,SyncConfig.INSTANCE.getDbProperty(SyncConstants.LIFE))),Updates.set(SyncAttrs.LAST_PING_TIME,System.currentTimeMillis()),new FindOneAndUpdateOptions().upsert(false).returnDocument(ReturnDocument.BEFORE)); if (FailedNode != null && FailedNode.getFailureTime() == 0) { syncNodeMapping.findOneAndUpdate(Filters.eq(SyncAttrs.ID,FailedNode.getId()),Updates.set(SyncAttrs.FAILURE_TIME,FailedNode.getLastPingTime())); } return FailedNode; }
public MngToOrclSyncWriter(BlockingQueue<Document> dataBuffer,MongoToOracleMap map,Syncmarker marker,CountDownLatch latch,boolean isRestrictedSyncEnabled,ObjectId eventId) { super(); this.dataBuffer = dataBuffer; this.map = map; this.marker = marker; this.latch = latch; this.isRestrictedSyncEnabled = isRestrictedSyncEnabled; this.eventId = eventId; this.options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.BEFORE); }
public String createNewLotCodeForTransportation() { Document updateLotCode = collection.findOneAndUpdate(exists("lotConfiguration.lastInsertionTransportation"),new Document("$inc",new Document("lotConfiguration.lastInsertionTransportation",1)),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); LaboratoryConfiguration laboratoryConfiguration = LaboratoryConfiguration.deserialize(updateLotCode.toJson()); return laboratoryConfiguration.getLotConfiguration().getLastInsertionTransportation().toString(); }
public String createNewLotCodeForExam() { Document updateLotCode = collection.findOneAndUpdate(exists("lotConfiguration.lastInsertionExam"),new Document("lotConfiguration.lastInsertionExam",new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); LaboratoryConfiguration laboratoryConfiguration = LaboratoryConfiguration.deserialize(updateLotCode.toJson()); return laboratoryConfiguration.getLotConfiguration().getLastInsertionExam().toString(); }
@Override public <T> T update(T t) { MongoModel mongoModel = (MongoModel) t; Document document = mongoModel.todocument(); MongoCollection<Document> collection = database.getCollection(t.getClass().getSimpleName()); BasicDBObject query = new BasicDBObject(MongoModel.OID,mongoModel.getobjectId()); collection.findOneAndUpdate(query,document),(new FindOneAndUpdateOptions()).upsert(true)); return t; }
@Override public FindOneAndUpdateOptions toFindOneAndUpdateOptions() { final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.bypassDocumentValidation(!validateDocuments); setMaxTime(options); setProjection(options); options.returnDocument(ret); setSort(options); options.upsert(upsert); return options; }
@Test public void findOneAndUpdate() { insertOneWithBulk(); Assert.assertNotNull(coll.findOneAndUpdate(Filters.eq("name","DELETEME"),new Document("name","UDPATED")))); Assert.assertNotNull(coll.findOneAndUpdate(Filters.eq("name","UDPATED"),"AGAIN")),new FindOneAndUpdateOptions())); coll.deleteMany(Filters.eq("name","AGAIN")); }
@Override public void put(String key,String value) { MongoCollection<Document> collection = getCollection(); Document query = new Document(KEY,key); Document toPut = new Document($SET,new Document(KEY,key).append(VALUE,value)); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.BEFORE); Document result = collection.findOneAndUpdate(query,toPut,options); if (needsFolderHandling && result == null) { dirRepo.registerParentage(key); } }
private void saveDocument(String key,String column,Object val) { registerKey(key); MongoCollection<Document> collection = getCollection(key); Document dbkey = new Document(ROWKEY,key).append(COLKEY,column); Document dbval = new Document($SET,new Document(ROWKEY,column).append(VALKEY,val)); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER); try { @SuppressWarnings("unused") Document ret = collection.findOneAndUpdate(dbkey,dbval,options); } catch (MongoException me) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,new ExceptionToString(me)); } }
/** * Returns the next epoch available and advances the counter. Guaranteed to * be unique for the given collection. If the epoch document does not * already exist a new one is created and the first epoch returned will be * 1L. * * @param collection * - the MongoCollection to the get next epoch for * @return Long - a unique epoch value for this collection */ public static Long nextEpoch(final MongoCollection<Document> collection) { final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER); MongoRetryWrapper<Long> wrapper = new MongoRetryWrapper<Long>() { public Long action(FindIterable<Document> cursor) { Document ret = collection.findOneAndUpdate(getEpochQueryObject(),getIncUpdateObject(getUpdateObject()),options); return (Long) ret.get(SEQ); } }; return wrapper.doAction(); }
@Override public Observable<TDocument> findOneAndUpdate(final Bson filter,final Bson update,final FindOneAndUpdateOptions options) { return RxObservables.create(Observables.observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndUpdate(filter,options,callback); } }),observableAdapter); }
@ExtDirectMethod public void sendPassordResetEmail(String userId) { String token = UUID.randomUUID().toString(); User user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.eq(CUser.id,userId),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); this.mailService.sendPasswortResetEmail(user); }
@Override public void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response,Authentication authentication) throws IOException,servletexception { Map<String,Object> result = new HashMap<>(); result.put("success",true); MongoUserDetails userDetails = (MongoUserDetails) authentication.getPrincipal(); if (userDetails != null) { User user; if (!userDetails.isPreAuth()) { user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.eq(CUser.id,userDetails.getUserDbId()),Updates.set(CUser.lastAccess,new Date()),new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER)); } else { user = this.mongoDb.getCollection(User.class) .find(Filters.eq(CUser.id,userDetails.getUserDbId())).first(); } result.put(SecurityService.AUTH_USER,new UserDetailDto(userDetails,user,CsrfController.getCsrftoken(request))); } response.setCharacterEncoding("UTF-8"); response.getWriter().print(this.objectMapper.writeValueAsstring(result)); response.getWriter().flush(); }
@Override public Publisher<TDocument> findOneAndUpdate(final Bson filter,final FindOneAndUpdateOptions options) { return new ObservabletoPublisher<TDocument>(observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndUpdate(filter,callback); } })); }
@Override public Publisher<TDocument> findOneAndUpdate(final ClientSession clientSession,final Bson filter,final FindOneAndUpdateOptions options) { return new ObservabletoPublisher<TDocument>(observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndUpdate(clientSession,filter,callback); } })); }
public void setEncryptedPassword(ObjectId id,byte[] pass) { connectionInfo.findOneAndUpdate( Filters.and(Filters.eq(String.valueOf(ConnectionInfoAttributes._id),id)),Updates.set(String.valueOf(ConnectionInfoAttributes.password),pass),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public SyncNode getNodeDetails(SyncNode nodeMapper) { Bson filter = Filters.eq(SyncAttrs.UUID,nodeMapper.getUUID()); logger.info("Getting node with filter " + filter); return syncNodeMapping.findOneAndUpdate(filter,Updates.unset(SyncAttrs.FAILURE_TIME),new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public void saveFlow(FlowEntity flowEntity) { if (flowEntity.getId() == null) { Integer nextId; Document lastFlow = collection.find() .projection(new Document("flow_id",1)) .sort(new Document("flow_id",-1)) .limit(1) .first(); if (lastFlow == null) { nextId = 1; } else { nextId = lastFlow.getInteger("flow_id") + 1; } flowEntity.setId(nextId); } Document filter = new Document() .append("flow_id",flowEntity.getId()); List<Document> conditionList = flowEntity.getConditionList() .stream() .map(conditionEntity -> new Document() .append("dev_id",conditionEntity.getDevId()) .append("dev_type",conditionEntity.getDevType()) .append("type",conditionEntity.getType()) .append("parameter",conditionEntity.getParameter())) .collect(Collectors.toList()); List<Document> actionList = flowEntity.getActionList() .stream() .map(conditionEntity -> new Document() .append("dev_id",conditionEntity.getParameter())) .collect(Collectors.toList()); Document entityDocument = new Document() .append("$set",new Document() .append("flow_id",flowEntity.getId()) .append("name",flowEntity.getName()) .append("order_num",flowEntity.getorderNum()) .append("conditions",conditionList) .append("actions",actionList) ); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER) .upsert(true); collection.findOneAndUpdate(filter,entityDocument,options); }
private void setSort(final FindOneAndUpdateOptions options) { if(sort != null) { options.sort(sort); } }
private void setProjection(final FindOneAndUpdateOptions options) { if(projection != null) { options.projection(projection); } }
private void setMaxTime(final FindOneAndUpdateOptions options) { if(maxTime != null) { options.maxTime(maxTime.getLeft(),maxTime.getRight()); } }
@Override public void invalidate() { Document invalidator = getInvalidator(); getIdGenCollection().findOneAndUpdate(getQueryObject(),invalidator,new FindOneAndUpdateOptions().upsert(true)); }
public void makeValid() { Document invalidator = getRevalidator(); getIdGenCollection().findOneAndUpdate(getQueryObject(),new FindOneAndUpdateOptions().upsert(true)); }
findByIdAndRemove无法在Mongoose中同时删除多个文档
最后我用deleteMany()解决了它 https://mongoosejs.com/docs/api.html#model_Model.deleteMany
findOneAndUpdate 在 mongodb 中不起作用
您正尝试使用在架构中定义为 ObjectId 类型的 _id
字段进行匹配。
因此,在您的查询中,尝试使用 ObjectId 类型进行搜索。
let ObjectId = require('mongoose').Types.ObjectId;
let profileUrl = 'example'
UserSchemaModel.findOneAndUpdate({_id: new ObjectId(userId)},{
$set: {
profileUrl: profileUrl
}
},{new:true}).then((updatedUser:UserModel) => {
console.log(updatedUser.profileUrl)
})
关于Mongoose findByIdAndUpdate upsert在初始插入时返回空文档和mongoose find报错的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Apollo graphql 和 Mongoose findOneUpdate 文档、com.mongodb.client.model.FindOneAndUpdateOptions的实例源码、findByIdAndRemove无法在Mongoose中同时删除多个文档、findOneAndUpdate 在 mongodb 中不起作用等相关内容,可以在本站寻找。
本文标签: