id在mongodb数据库中保存为[object]

时间:2015-09-14 18:19:07

标签: javascript json node.js mongodb

我正在学习MEAN堆栈,同时通过构建10个项目来学习node.js,我正在尝试完成elearn项目教程 注册课时有一个问题:class_id:[Object]

不要担心下面的代码,以防你想看看。

Json记录了如何保存:

{ _id: 55f708806a7390500cb421ce,
  first_name: 'Madhur',
  last_name: 'Gupta',
  email: 'madhurgupta@mymail.com',
  username: 'madhur',
  __v: 0,
  classes:
   [ { class_title: 'HTML 101',
       _id: 55f708b46a7390500cb421d5,
       class_id: [Object] },
     { class_title: 'HTML 101',
       _id: 55f708be6a7390500cb421d6,
       class_id: [Object] } ],          // This class_id: [Object]
  address:
   [ { street_address: '007, Some street',
       city: 'My City',
       state: 'My State',
       zip: '141551',
       _id: 55f708806a7390500cb421cf } ] }

这是架构

var mongoose = require('mongoose');

//讲师模式

var instructorSchema = mongoose.Schema({
  first_name: {
    type: String
  },
  last_name: {
    type: String
  },
  address: [{
      street_address: {type: String},
      city: {type: String},
      state: {type: String},
      zip: {type: String}
  }],
  username: {
    type: String
  },
  email: {
    type: String
  },
  classes: [{
      class_id: {type: [mongoose.Schema.Types.ObjectId]},
      class_title: {type: String}
    }]
});

var Instructor = module.exports = mongoose.model('instructor', instructorSchema);

module.exports.getInstructorByUsername = function(username, callback) {
  var query = { username: username };
  Instructor.findOne(query, callback);
}

// Register instructor for Class
module.exports.register = function(info, callback) {
    instructor_username = info['instructor_username'];
    class_id = info['class_id'];
    class_title = info['class_title'];

    var query = {username: instructor_username};
    Instructor.findOneAndUpdate(
      query,
      {$push: {"classes": {class_id: class_id, class_title: class_title}}},
      {safe: true, upsert: true},
      callback
    );
}

这是类架构:

var mongoose = require('mongoose');

// Class Schema
var classSchema = mongoose.Schema({
  title: {
    type: String
  },
  description: {
    type: String
  },
  instructor: {
    type: String
  },
  lessons: [{
    lesson_number: {type: Number},
    lesson_title: {type: String},
    lesson_body: {type: String}
  }]
});

var Class = module.exports = mongoose.model('Class', classSchema);

// Fetch All Classes
module.exports.getClasses = function(callback, limit) {
  Class.find(callback).limit(limit);
}

// Fetch Single Class
module.exports.getClassesById = function(id, callback) {
  Class.findById(id, callback);
}

module.exports.addLesson = function(info, callback) {
  class_id = info['class_id'];
  lesson_number = info['lesson_number'];
  lesson_title = info['lesson_title'];
  lesson_body = info['lesson_body'];

  Class.findByIdAndUpdate(
      class_id,
      {$push: {"lessons" : {lesson_number: lesson_number, lesson_title: lesson_title, lesson_body: lesson_body}}},
      {safe: true, upsert: true},
      callback
    );
}

这是Instructor.js路由文件

var express = require('express');
var router = express.Router();

Class = require('../models/class');
Instructor = require('../models/instructor');
User = require('../models/user');

/* GET home page. */
router.get('/classes', ensureAuthenticated, function(req, res, next) {
  Instructor.getInstructorByUsername(req.user.username,
    function(err, instructor) {
    if (err) {
      console.log(err);
      res.send(err);
    } else {
      res.render('instructors/classes', {
        'instructor' : instructor
      });
    }
  });
});

router.post('/classes/register', function(req, res) {
  info = [];
  info['instructor_username'] = req.user.username;
  info['class_id'] = req.body.class_id;
  info['class_title'] = req.body.class_title;

  Instructor.register(info, function(err, instructor) {
    if (err) throw err;
    console.log(instructor);
  });
  req.flash('success', 'You are now registered to teach this class');
  res.redirect('/instructors/classes');
});

// Display the form to add classes
router.get('/classes/:id/lessons/new', ensureAuthenticated, function(req, res, next) {
  res.render('instructors/newlesson',
    {'class_id': req.params.id});
});

router.post('/classes/:id/lessons/new', ensureAuthenticated, function(req, res, next) {
  // Get Form Values
  var info = [];
  info['class_id'] = req.params.id;
  info['lesson_number'] = req.body.lesson_number;
  info['lesson_title'] = req.body.lesson_title;
  info['lesson_body'] = req.body.lesson_title;

  Class.addLesson(info, function(err, lesson) {
    console.log('Lesson added');
  });
  req.flash('success', 'Lesson Added');
  res.redirect('/instructors/classes');
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/users/login');
}

module.exports = router;

这是classes.js路由文件

var express = require('express');
var router = express.Router();

Class = require('../models/class');



router.get('/', function(req, res, next) {
  Class.getClasses(function(err, classes){
    if(err){
      console.log(err);
      res.send(err);
    } else {
      res.render('classes/index', { "classes": classes });
    }
  }, 3);
});

router.get('/:id/details', function(req, res, next) {
  Class.getClassesById([req.params.id],function(err, classname){
    if(err){
      console.log(err);
      res.send(err);
    } else {
      res.render('classes/details', { "class": classname });
    }
  });
});

router.get('/:id/lessons', function(req, res, next) {
  Class.getClassesById([req.params.id],function(err, classname){
    if(err){
      console.log(err);
      res.send(err);
    } else {
      res.render('classes/;esspms', { "class": classname });
    }
  });
});

router.get('/:id/lessons/:lesson_id', ensureAuthenticated, function(req, res, next) {
  Class.getClassesById([req.params.id],function(err, classname) {
    if(err){
      var lesson;
      res.send(err);
    } else {
        // loop through lessons to see if they equal :lesson_id
        for (i = 0; i < classname.lessons.length; i++) {
          if (classname.lessons[i].lesson_number == req.params.lesson_id) {
            lesson = classname.lessons[i];
          }
        }
        res.render('classes/lesson', {
          'class' : classname,
          'lesson' : lesson
        });
    }
  });
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
 }
  res.redirect('/users/login');
}

module.exports = router;

这是Package.json文件:

{
  "name": "eLearn",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodemon ./bin/www"
  },
  "dependencies": {
    "async": "^1.0.0",
    "bcryptjs": "*",
    "body-parser": "~1.8.1",
    "connect-flash": "*",
    "cookie-parser": "~1.3.3",
    "debug": "~2.0.0",
    "express": "~4.9.0",
    "express-handlebars": "*",
    "express-messages": "*",
    "express-session": "*",
    "express-validator": "*",
    "jade": "~1.6.0",
    "mongodb": "*",
    "mongoose": "*",
    "morgan": "~1.3.0",
    "passport": "*",
    "passport-http": "*",
    "passport-local": "*",
    "serve-favicon": "~2.1.3"
  }
}

1 个答案:

答案 0 :(得分:0)

根据您的示例,您不应将class_idclasses中的每个instructorSchema字段声明为数组类型。

最有可能instructorSchema看起来像这样:

var instructorSchema = mongoose.Schema({
  ...,
  classes: [{
      class_id: {type: mongoose.Schema.Types.ObjectId},
      class_title: {type: String}
  }]
});