Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

mongoose findoneandupdate

// note: this uses async/await so it assumes the whole thing 
// is in an async function 

const doc = await CharacterModel.findOneAndUpdate(
  { name: 'Jon Snow' },
  { title: 'King in the North' },
  // If `new` isn't true, `findOneAndUpdate()` will return the
  // document as it was _before_ it was updated.
  { new: true }
);

doc.title; // "King in the North"
Comment

findOneAndUpdate mongoose

const Character = mongoose.model('Character', new mongoose.Schema({
  name: String,
  age: Number
}));

await Character.create({ name: 'Jean-Luc Picard' });

const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };

// `doc` is the document _before_ `update` was applied
let doc = await Character.findOneAndUpdate(filter, update);
doc.name; // 'Jean-Luc Picard'
doc.age; // undefined

doc = await Character.findOne(filter);
doc.age; // 59
Comment

findone and update mongoose

// Using queries with promise chaining
Model.findOne({ name: 'Mr. Anderson' }).
  then(doc => Model.updateOne({ _id: doc._id }, { name: 'Neo' })).
  then(() => Model.findOne({ name: 'Neo' })).
  then(doc => console.log(doc.name)); // 'Neo'

// Using queries with async/await
const doc = await Model.findOne({ name: 'Neo' });
console.log(doc.name); // 'Neo'
Comment

PREVIOUS NEXT
Code Example
Javascript :: react is there a safe area view for android 
Javascript :: btn.addeventlistener 
Javascript :: jquery sort listing alphabetically 
Javascript :: javascript element read attribute 
Javascript :: how to convert json result into datatable c# 
Javascript :: postmessage from iframe to parent 
Javascript :: gulp runSequence 
Javascript :: get placeholder innerhtml 
Javascript :: reload page in react router dom v6 
Javascript :: js read from json1 
Javascript :: initialize function javascript 
Javascript :: current date minus days javascript 
Javascript :: js get object keys 
Javascript :: copy to clipboard using javascript 
Javascript :: icon refresh material ui 
Javascript :: js how to remove # from any url using js 
Javascript :: .sort javascript 
Javascript :: regex to match string not in between quotes 
Javascript :: javascript remove underscore and capitalize 
Javascript :: how to control playback speed in javascript 
Javascript :: copy to clipboard javascript dom 
Javascript :: validate password regex 
Javascript :: how to find the smallest two numbers in an array javascript 
Javascript :: emit resize event in angular 
Javascript :: javascript conver time into 24 hour format 
Javascript :: momentTimeZone 
Javascript :: anonymous function jquery 
Javascript :: hot reload problem react 17 
Javascript :: how to put text in the center react native 
Javascript :: javascript average of arguments 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =