0

I am new in mongoose and I'm facing some problem in it.

After running the following code, neither success nor error message is shown. And when I browse the webpage, there is no response.

Is there any problem in my code?

const http = require("http");
const mongoose = require("mongoose");

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/node_tut", { useMongoClient: true});

const StudentSchema = new mongoose.Schema({
    first_name: { type: String, required: true },
    last_name:  { type: String, required: true },
    class:      { type: String, required: true },
    class_num:  { type: Number, min: 1, required: true }
});

let Student = mongoose.model('student', StudentSchema);

let peter = new Student({
    first_name: "Peter",
    last_name: "Chan",
    class: "1A",
    class_num: 2
});

peter.save((err) => {
    if(err){
        console.log("Error inserting Peter");
        return;
    }
    console.log("inserting Peter");
});

let mary = new Student({
    first_name: "Mary",
    last_name: "Hung",
    class: "1A",
    class_num: 6
});

mary.save((err) => {
    if(err){
        console.log("Error inserting Mary");
        return;
    }
    console.log("inserting Mary");
});


const server = http.createServer((req, res) => {
    // Send the HTTP header 
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    res.writeHead(200, {'Content-Type': 'text/plain'});
    console.log("request");
    Student.find({}, (err, students) => {
        console.log("result founded");
        if(err){
            res.end(err);
            return;
        }
        res.end(students.toString());
    });
});

server.listen(3000);
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • 1
    I think you mean `res.json(students)` there. Also see [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) since you have several `.save()` calls in there which actually need to wait for their callback to complete before it is guaranteed that anything is actually inserted. If you hit the server very quickly after starting the program, then nothing would be there. – Neil Lunn Jun 27 '17 at 06:59
  • 1
    Also, if you are using `useMongoClient : true` to work around [this issue](https://github.com/Automattic/mongoose/issues/5399): don't. As you can see in the issue comments, when people set that option, their apps stop working. Either remove it and live with the deprecation warning, or downgrade to a previous version of Mongoose. – robertklep Jun 27 '17 at 07:05
  • Thanks @robertklep opinion that the code works after remove the {useMongoClient : true} option. – Calvin Wong Jun 27 '17 at 07:40

0 Answers0