猫鼬:无法插入/查找记录

时间:2017-06-27 06:55:54

标签: node.js mongoose

我是猫鼬新手,我面临一些问题。

运行以下代码后,既不显示成功也不显示错误消息。当我浏览网页时,没有回复。

我的代码有问题吗?

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

0 个答案:

没有答案