无法将引用的对象属性引用到console.log()

时间:2017-07-30 22:50:15

标签: javascript node.js

我无法从其他对象中获取引用数据。

我目前有两种型号......

var mongoose = require(“mongoose”);

STUDENT:

var gameSchema = new mongoose.Schema(
    {
        name: String,
        courses:   [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref:  "Course"
            }
        ]
    });

module.exports = mongoose.model("Student", gameSchema);

课程:

var mongoose = require("mongoose");

var courseSchema = new mongoose.Schema (
    {
        name: String,
        student: [
            {
                id: 
                {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: "Student"
                },
                name: String
            }
        ]
    }
);

module.exports = mongoose.model("Course", courseSchema);

当我在console.log(foundStudent.courses [0] .name)时,我得到了未定义,我无法弄清楚为什么......

app.post("/students/:id", function(req, res){
   Student.findById(req.params.id, function(err, foundStudent){
       if(err){
           console.log(err);
       } else {
          Course.create(req.body.class, function(err, createdCourse){
              if(err){
                  console.log(err);
              } else {

                    createdCourse.student.push(foundStudent);
                    createdCourse.save();

                    foundStudent.courses.push(createdCourse);
                    foundStudent.save();
                    res.redirect("/students/" + req.params.id);
              }
          });
       }
   });
});

这是展示页......

<div>
    <h1>Student Profile</h1>
    <h2>Name: <%=student.name%></h2>
    <div>
        <h3>Classes:
            <form action="/students/<%= student._id %>" method="POST">
                <% student.courses.forEach(function(course){ %>
                    <li><p><%= course.name %></p></li>
                <% }); %>
            <a href="/students/<%=student._id%>/courses/new">Add Course</a>
            </form>
        </h3>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

我使用mockgoosemocha添加了一个简单的测试套件来展示DocumentQuery.populate的用法。

学生模式

const schema = mongoose.Schema({
    name: String,
    courses: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Course' }]
});

module.exports = mongoose.model('Student', schema);

课程架构

const schema = mongoose.Schema({
    name: String,
});

module.exports = mongoose.model('Course', schema);

测试套件

const mongoose = require('mongoose');
const mockgoose = new (require('mockgoose').Mockgoose)(mongoose);

const { assert, expect } = require('chai');

const Student = require('../models/student');
const Course = require('../models/course');

var student = null;

before(done => {
    mockgoose.prepareStorage().then(res => {
        mongoose.connect('mongodb://test/testDB', (err) => {
            if (err) {
                return done(err);
            }

            student = new Student({
                name: 'Shane'
            });

            student.save(err => {
                done(err);
            });
        });
    });
});

describe('population', () => {
    it('should populate referenced collection', done => {
        let course = new Course({
            name: 'Applied Sciences'
        });

        // save mock course
        course.save(err => {
            if (err) {
                return done(err);
            }

            student.courses.push(course._id);

            // push changes
            student.save(err => {
                if (err) {
                    return done(err);
                }

                // you can use any other find method that returns a DocumentQuery object
                Student.findOne({
                    name: 'Shane'
                }).populate('courses').exec((err, res) => {
                    if (err) {
                        return done(err);
                    }

                    expect(res.courses).to.have.lengthOf(1);

                    assert.equal(res.courses[0].name, 'Applied Sciences');

                    done();
                });
            });
        });
    });
});

使用mocha运行上述内容时,将传递断言,并为学生对象提供一门课程。

另一件需要注意的事情是,Schema.create用于一次推送一批对象。无论是否应使用doc.saveSchema.create,都值得商榷。 create方法实际上只接受一个文档数组,但是在传递一个对象时有一个回退。它调用保存在每个文档对象上并在保存所有文档时解析。