Advanced Node.js Development
上QQ阅读APP看书,第一时间看更新

Targeting the documents using ID

Next up, I'm going to write the other statement. We're going to target the Users collection once again. Now, we're going to go ahead and use the findOneAndDelete method. In this particular case, I am going to be deleting the Todo where the _id equals the ObjectId I have copied to the clipboard, which means I need to create a new ObjectID, and I also need to go ahead and pass in the value from the clipboard inside of quotes.

db.collection('Users').deleteMany({name: 'Andrew'});

db.collection('Users').findOneAndDelete({
  _id: new ObjectID("5a86978929ed740ca87e5c31")
})

Either single or double would work. Make sure the capitalization of ObjectID is identical to what you have defined, otherwise this creation will not happen.

Now that we have the ID created and passed in as the _id property, we can go ahead and tack on a then callback. Since I'm using findOneAndDelete, I am going to print that document to the screen. Right here I'll get my argument, results, and I'm going to print it to the screen using our pretty- printing method,console.log(JSON.stringify()), passing in those three arguments, the results, undefined, and the spacing, which I'm going to use as 2.

db.collection('Users').deleteMany({name: 'Andrew'});

db.collection('Users').findOneAndDelete({
  _id: new ObjectID("5a86978929ed740ca87e5c31")
}).then((results) => {
  console.log(JSON.stringify(results, undefined, 2));
});

With this in place, we are now ready to go.