Beta - Mongoose Challenges - Create and Save a Record of a Model

Beta - Mongoose Challenges - Create and Save a Record of a Model
0

#1

Has anyone completed the beta mongoose challenges?

I am stuck on this one.

The code have have is this:

const mongoose = require('mongoose');
const mongoDB = require('mongodb');
const Schema = mongoose.Schema;

mongoose.connect(process.env.MONGO_URI);
var personSchema = new Schema({
  name: String,
  age: Number,
  favouriteFoods: [String]

})

const Person = mongoose.model('person', personSchema)

var person = new Person({name: 'Ben', age: 23, favouriteFoods: ['tuna', 'bread']})
person.save((err, data)=>{
if (err){ console.log(err)}})

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a 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.


#3

I had the same problem, you have to use the save method inside the createAndSavePerson function:

var createAndSavePerson = function(done) {
 var person = new Person({name: 'Ben', age: 23, favouriteFoods: ['tuna', 'bread']})
 person.save((err, data)=>{
  if (err) return done(err)
  return done(null, data)
 }
}


#4

I’m having a problem getting the tests to pass. The tests keep timing out.
Does anyone see anything wrong with the following code:

var createAndSavePerson = function(done) {
  const person = new Person({name: 'Joe', age: 21, favoriteFoods: ['pizza', 'burger']});
  person.save((err, data) => err ? done(err) : done(null, data));
};

#5

I haven’t actually tried to make this work for the exercise , but i’m wondering why a new Person is being declared when the personSchema is already referencing a new Schema to be created . To me, it looks like only the following should be enough to add the object to the dB

const data = {name: 'Ben', age: 23, favouriteFoods: ['tuna', 'bread']}
Person.create(data,(err,newPerson)=>{
      if(err){throw err}
     console.log(newPerson, " Successfully Added to dB!")  
})

Again, apologies if this doesn’t directly address the question, since I haven’t had a chance to look at the exercise, but if the point is just to add a new person per the given schema , shouldn’t the above suffice?


#6

I think the only purpose of the “personSchema” was to use it to create the “Person” model. In order to create a document you need to use “new Person” or “Person.create” as you mentioned. Its my understanding that calling “new Person” and then calling “save” essentially does the same thing as using “Person.create” (Constructing documents).

Based on that logic I think that your snippet essentially does the same thing as mine except that the exercise requires you to use the “done” callback so the tests will work.

Thanks for your feedback. Let me know if anything I said sounds wrong.


#7

Ah, good to know @JMagers i’ve always used the .create method rather than the .save or maybe come to think of it I may have used it sparingly for saving authenticated users before , anyway a potential issue that I see in your code not passing maybe that your ternary operator is not returning any results, so maybe you can try:

person.save((err, data) => return(err ? done(err) : done(null, data)));

If that doesn’t solve it, then see if the solution above @dnlnav works, if it does it must be related with the ternary operator as that is the only difference I see and you may need to refactor to see what’s up with your ternary operator


#8

I refactored the code to avoid using the ternary operator like you suggested.

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);
  });
};

Unfortunately the tests still result in the same timeout failure that the previous code did. This should be identical to the solution provided by @dnlnav but it still doesn’t work. I’m wondering if maybe there is a bug in the test itself. Thanks again.


#9

ok @JMagers , had a chance to setup and go thru the lessons, the tests passed for me so I don’t think there is any bug in the tests, fyi the OP has a spelling error in favoriteFoods that won’ allow the tests to go thru, anyway here is the entire code that passed for me with very minimal change to the last code you posted

const mongoose = require('mongoose')
mongoose.connect(process.env.MONGO_URI)

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

const Person = mongoose.model('Person', personSchema)

const createAndSavePerson = function(done) {
  const person = new Person({name: 'Joe', age: 21, favoriteFoods: ['pizza', 'burger']});
  person.save((err, data) => {
    if (err) {
      done(err);
    }
    done(null, data);
  });
};

I will now try to refactor and make it work with the ternary operator

Edit : ok This passes for me too, which as far as I can tell is identical to your original code

const mongoose = require('mongoose')
mongoose.connect(process.env.MONGO_URI)

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

const Person = mongoose.model('Person', personSchema)

const createAndSavePerson = function(done) {
  const person = new Person({name: 'Joe', age: 21, favoriteFoods: ['pizza', 'burger']});
  person.save((err, data) => err ? done(err) : done(null,data));
};

Unless there is a difference in what you have written before the createAndSavePerson function, which I haven’t seen so can’t tell, other than that don’t know what to tell ya…


#10

I got the tests to pass! Thanks to your help I was able to eliminate the possibility that the problem had to with any of that code. Apparently the password for my mongo database had some special characters in it that are not allowed in a URI. I would of thought that this kind of error would have been caught in the earlier tests but apparently not.

Thanks again.


#11

hmmm… that’s weird because a db connection string error should have shown in your glitch log , you can access it by clicking log on the top left of your screen (If you haven’t done so already) . Anyway, good that you solved it…


#12

Was stuck here too until I saw this. Thank you.


#13

I’m in a three days trying to solve this exercise. Just receive: “Creating an instance from a mongoose schema should succeed” :frowning:


#14

Arrow functions “return” implicitly unless you use curly brackets

(err, data) => err ? done(err) : done(null, data)

or with return

person.save((err, data) => {
  return err ? done(err) : done(null, data)
};