2015-06-19 1 views
0

Я пытаюсь практиковать Мангуст и Node JS, я хочу использовать комментарий схему в статье схемы и при запуске сервера, он просто выдает ошибку, как это:NodeJS - Mongoose документ вложения

недопустимое значение для схемы массива пути comments

Вот мой комментарий модель

module.exports = function(mongoose) { 

    var Schema = mongoose.Schema; 

    var CommentSchema = new Schema({ 
     text: String, 
     author: String, 
     createDate: { 
      type: Date, 
      default: Date.now 
     } 
    }); 

    console.log("********");  
    console.log(CommentSchema); 
    console.log("********"); 

    mongoose.model('Comment', CommentSchema); 
}; 

И моя статья модель:

module.exports = function(mongoose){ 
    var Schema = mongoose.Schema; 
    var Comment = require("./Comment"); 

    console.log("--------"); 
    console.log(mongoose); 
    console.log("--------"); 

    var ArticleSchema = new Schema({ 
     title: String, 
     content: String, 
     author: String, 
     comments: [Comment.schema], 
     createDate: { 
      type: Date, 
      default: Date.now 
     } 
    }); 
    mongoose.model('Article', ArticleSchema); 
}; 

Они находятся в одной папке под названием «модели».

И, наконец, мой app.js показать привязки:

var express = require('express'); 
var morgan = require("morgan"); 
var methodOverride = require("method-override"); 
var utils = require("./lib/utils"); 
var config = require("config"); 
var bodyParser = require('body-parser'); 
var app = express(); 
var mongoose = require('mongoose'); 
var mongooseConnection = utils.connectToDatabase(mongoose, config.db); 
var routes = require('./routes/index'); 
var users = require('./routes/users'); 

var app = express(); 

// view engine setup 
app.set("port", process.env.PORT || 3000); 

app.use(express.static(__dirname + '/public')); 
app.use(morgan('dev')); 
app.use(bodyParser()); 
app.use(methodOverride()); 

app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 
app.set('view options', { layout: true}); 

require("./controllers/ArticleController")(app, mongooseConnection); 
require("./controllers/CommentController")(app, mongooseConnection); 
require("./controllers/IndexController")(app, mongooseConnection); 

require("./models/Article")(mongooseConnection); 
require("./models/Comment")(mongooseConnection); 
require("./models/User")(mongooseConnection); 

app.listen(app.get("port"), function(){ 
    console.log("Express server listening on port" + app.get("port")); 
}); 

Спасибо.

+0

Я не помню необходимости передать соединение схема/модель. Просто избавитесь от этого материала и экспортируйте модель. –

ответ

2

На вашем ./models/Article.js вашего переменной Comment является функцией (вы должны быть вызовом его скобка проходя мимо переменными мангустов), вместо модели Комментария:

module.exports = function(mongoose){ 
    // some code .. 

    var Comment = require("./Comment"); 

    // some code .. 
}; 

И даже если вы выполняете вашу функцию выше проходных переменные мангустов в вашем ./models/Comments.js в вашей функции, вы в основном возвращаетесь ничего:

module.exports = function(mongoose) { 
    // some code .. 

    mongoose.model('Comment', CommentSchema); 
}; 

Итак, попробуйте этот пример, который я создал ниже.

комментарий модель в ./models/Comment.js:

module.exports = function (mongoose) { 
    var CommentSchema = new mongoose.Schema({ 
    text: String, 
    author: String, 
    createDate: {type: Date, default: Date.now} 
    }); 

    return mongoose.model('Comment', CommentSchema); 
}; 

Статья Модель на ./models/Article.js:

module.exports = function (mongoose) { 
    var Comment = require('./Comment')(mongoose); 

    var ArticleSchema = new mongoose.Schema({ 
    title: String, 
    content: String, 
    author: String, 
    comments: [Comment.schema], 
    createDate: {type: Date, default: Date.now} 
    }); 

    return mongoose.model('Article', ArticleSchema); 
}; 

Главный файл на ./app.js:

var mongoose = require('mongoose'); 

mongoose.connect('mongodb://localhost:27017/mongoose_sky'); 

var Article = require('./models/Article.js')(mongoose); 

var article = new Article({ 
    title: 'my article', 
    content: 'this is my awesome article', 
    author: 'wilson', 
    comments: [ 
    { 
     text: 'hey your article is great', 
     author: 'doug' 
    }, 
    { 
     text: 'hillarious!', 
     author: 'john' 
    } 
    ] 
}); 

article.save(function (err) { 
    if (!err) { 
    console.log('article was saved'); 
    console.log(article); 
    } 
});