Help me with Perform New Updates on a Document Using model.findOneAndUpdate()

Help me with Perform New Updates on a Document Using model.findOneAndUpdate()
0

#1

Please help me with this!
My code:
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGO_URI); /* Hey there! Add a Database connection inside MONGOURI in .env file first. */

var personSchema = new mongoose.Schema({
  name: String,
  age: Number,
  favoriteFoods: [String]

})

const Person = mongoose.model('Person', personSchema)
const Model = mongoose.model('Person', personSchema)
 
var createAndSavePerson = function(done) {
  const person = new Person({name: 'Joe', age: 21, favoriteFoods: ['pizza', 'burger']});
  person.save((err, data) => {
    if (err) {
      return done(err);
    }
    return done(null, data);
  });
};
// running test
//Person Model is not correct <--  The problem is this
// tests completed
// Create a `document` instance using the `Person` constructor you build before.
// Pass to the constructor an object having the fields `name`, `age`,
// and `favoriteFoods`. Their types must be conformant to the ones in
// the Person `Schema`. Then call the method `document.save()` on the returned
// document instance, passing to it a callback using the Node convention.
// This is a common pattern, all the **CRUD** methods take a callback 
// function like this as the last argument.

// - Example -
// ...
// person.save(function(err, data) {
//    ...do your stuff here...
// });



/** 4) Create many People with `Model.create()` */

// Sometimes you need to create many Instances of your Models,
// e.g. when seeding a database with initial data. `Model.create()`
// takes an array of objects like [{name: 'John', ...}, {...}, ...],
// as the 1st argument, and saves them all in the db.
// Create many people using `Model.create()`, using the function argument
// 'arrayOfPeople'.

var createManyPeople = function(arrayOfPeople, done) {
Person.create(arrayOfPeople, (err, data) => {
if(err) {
done(err);
}
done(null, data);
})
};


/** # C[R]UD part II - READ #
/*  ========================= */

/** 5) Use `Model.find()` */

// Find all the people having a given name, using `Model.find() -> [Person]`
// In its simplest usage, `Model.find()` accepts a **query** document (a JSON
// object ) as the first argument, and returns an **array** of matches.
// It supports an extremely wide range of search options. Check it in the docs.
// Use the function argument `personName` as search key.
var findPeopleByName = function (personName, done) 
 {
  // Our Model name is Person, and find is the method we have to use. So... Don't use findById, just use find()
   // And mongodb takes a query in this format: {key: value} so we will query like this {"name" : personName}
  Person.find({ "name" : personName }, (err, foundPerson) => {
    if (err) {
      done(err);
    }
    done(null, foundPerson);
    //Okay?
    // Did it work? Is this what you were trying to do?
  });
   
};

//Did not work

/** 6) Use `Model.findOne()` */

// `Model.findOne()` behaves like `.find()`, but it returns **only one**
// document, even if there are more. It is especially useful
// when searching by properties that you have declared as unique.
// Find just one person which has a certain food in her favorites,
// using `Model.findOne() -> Person`. Use the function
// argument `food` as search key

var findOneByFood = function(food, done) {
  Person.findOne({favoriteFoods: food}, function(err, data) {
    if(err) return done(err);
    return done(null, data);
  });  
};


/** 7) Use `Model.findById()` */

// When saving a document, mongodb automatically add the field `_id`,
// and set it to a unique alphanumeric key. Searching by `_id` is an
// extremely frequent operation, so `moongose` provides a dedicated
// method for it. Find the (only!!) person having a certain Id,
// using `Model.findById() -> Person`.
// Use the function argument 'personId' as search key.

var findPersonById = (personId, done) => {
  Model.findById(Person.personId, (err, data) => err ? done(err) : done(null, data)); 
};
/** # CR[U]D part III - UPDATE # 
/*  ============================ */

/** 8) Classic Update : Find, Edit then Save */

// In the good old days this was what you needed to do if you wanted to edit
// a document and be able to use it somehow e.g. sending it back in a server
// response. Mongoose has a dedicated updating method : `Model.update()`,
// which is directly binded to the low-level mongo driver.
// It can bulk edit many documents matching certain criteria, but it doesn't
// pass the edited document to its callback, only a 'status' message.
// Furthermore it makes validation difficult, because it just
// direcly calls the mongodb driver.

// Find a person by Id ( use any of the above methods ) with the parameter
// `personId` as search key. Add "hamburger" to the list of her `favoriteFoods`
// (you can use Array.push()). Then - **inside the find callback** - `.save()`
// the updated `Person`.

// [*] Hint: This may be tricky if in your `Schema` you declared
// `favoriteFoods` as an `Array` without specifying the type (i.e. `[String]`).
// In that case `favoriteFoods` defaults to `Mixed` type, and you have to
// manually mark it as edited using `document.markModified('edited-field')`
// (http://mongoosejs.com/docs/schematypes.html - #Mixed )

var findEditThenSave = function(personId, done) {
  let foodToAdd = 'hamburger';
  
  Person.findById(personId, (err, data) => {
    if (err) { 
      done(err) 
    }
    console.log(data);
    data.favoriteFoods.push(foodToAdd);
    data.save((err, data) => {
    if (err) 
    { 
      done(err) 
    }
else { 
  done(null, data) 
}
      
  });
    // done(null, data);
  });
  
  // done(null/*, data*/);
};

/** 9) New Update : Use `findOneAndUpdate()` */

// Recent versions of `mongoose` have methods to simplify documents updating.
// Some more advanced features (i.e. pre/post hooks, validation) beahve
// differently with this approach, so the 'Classic' method is still useful in
// many situations. `findByIdAndUpdate()` can be used when searching by Id.
//
// Find a person by `name` and set her age to `20`. Use the function parameter
// `personName ` as search key.
//
// Hint: We want you to return the **updated** document. In order to do that
// you need to pass the options document `{ new: true }` as the 3rd argument
// to `findOneAndUpdate()`. By default the method
// passes the unmodified object to its callback.

//
// http://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate
//
// findOneAndUpdate(filter, update, options)

var findAndUpdate = function(personName, doc) {
  var ageToSet = 20;
  
  Person.findOneAndUpdate(
    {"name": personName},
    {$set: {"age":ageToSet}},
    {new : true},
    function(err,done){
      if(err){
        console.log("Error Ocurred")
      }
      console.log(done)
    }    
)};

PLEASE HELP!


#2

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

In the future, please format your code as shown above when posting code to the forum.

Thank you.