2016-12-05 10 views
0

몽구스로 찾기를 수행 할 때 ObjectId 배열을 채우려고합니다. 여기 몽구스 채우기 ObjectId 배열 찾기

models/comment.js이다 : 여기

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var Comment = require('./comment'); 


// set up a mongoose model 
var QuestionSchema = new Schema({ 
    title: { 
     type: String, 
     unique: false, 
     required: true 
    }, 
    question: { 
     type: String, 
     required: true 
    }, 
    plus: { 
     type: Number, 
     required: true, 
     default: 0 
    }, 
    minus: { 
     type: Number, 
     required: true, 
     default: 0 
    }, 
    date: { 
     type: Date, 
     default: new Date() 
    }, 
    comments:[ 
     {type: Schema.Types.ObjectId, ref: 'Comment'} 
    ] 
}); 

module.exports = mongoose.model('Question', QuestionSchema); 

index.js

var express  = require('express'); 
var app   = express(); 
var request  = require('request-promise'); 
var bodyParser = require('body-parser'); 
var morgan  = require('morgan'); 
var mongoose = require('mongoose'); 
var passport  = require('passport'); 
var config  = require('./config/database'); // get db config file 
var User  = require('./models/user'); // get the mongoose model 
var Room  = require('./models/room'); // get the mongoose model 
var Comment = require('./models/comment'); // get the mongoose model 
var Question = require('./models/question'); // get the mongoose model 
var port  = process.env.PORT || 5000; 
var jwt   = require('jwt-simple'); 
var http  = require('http'); 
var io   = require('socket.io'); 
var server  = http.createServer(app); 
var io   = io.listen(server); 



// get our request parameters 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()); 

// log to console 
app.use(morgan('dev')); 

// Use the passport package in our application 
app.use(passport.initialize()); 

// Set the port 
app.set('port', port); 

//App files located in /public 
app.use(express.static(__dirname + '/public')); 

// views is the directory for all template files 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'ejs'); 

// The root url of the website serves the Angular app 
app.get('/', function (request, response) { 
    response.render('pages/index'); 
}); 

// connect to database 
mongoose.connect(config.database); 

// pass passport for configuration 
require('./config/passport')(passport); 

var roomService = require('./controllers/roomservice.js'); 
roomService.setup(io); 

// connect the api routes under /api/* 
app.use('/api', apiRoutes); 

// Start the Express app 
server.listen(app.get('port'), function() { 
    console.log('Node app is running on port', app.get('port')); 
}); 
여기

controllers/roomservice.js

이다 : 여기
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

// set up a mongoose model 
var CommentSchema = new Schema({ 
    comment: { 
     type: String, 
     unique: false, 
     required: true 
    }, 
    date: { 
     type: Date, 
     default: new Date() 
    }, 
}); 

module.exports = mongoose.model('Comment', CommentSchema); 

models/question.js이고
function RoomService(){ 
    var socketio; 
    var Comment = require('../models/comment'); // get the mongoose model 
    var Question = require('../models/question'); // get the mongoose model 
    var Room = require('../models/room'); // get the mongoose model 

    function setup(io){ 
     socketio = io; 
     socketio.on("connection", function(socket){ 
      socket.on('joinRoom', function(msg){ 
       console.log("joinRoom"); 
       socket.join(msg.room) 
       Question.find({}) 
        .exec(function(err, questions) { 
         for(var question in questions){ 
          for(var comment in questions[question].comments){ 
           questions[question].comments[comment] = Comment.find({ "_id": questions[question].comments[comment]}); 
          } 
         } 
         socket.emit("listQuestions", questions) 
       }); 
      }); 
      socket.on('addQuestion', function(msg){ 
       console.log("addQuestion"); 
       var question = new Question({ 
        title: msg.title, 
        question: msg.question 
       }); 
       // save the question 
       question.save(function(err) { 
        if (err) throw err; 
        io.to(msg.room).emit("addQuestion", question); 
       }); 
      }); 
      socket.on('addComment', function(msg){ 
       var comment = new Comment({ 
        comment: msg.comment 
       }); 
       // save the comment 
       Question.findOne({_id: msg.question}, function(err, question){ 
        if (err) throw err; 
        question.comments.push(comment); 
        question.save(function(err) { 
         if (err) throw err; 
         io.to(msg.room).emit("addComment", comment); 
         console.log(question); 
        }); 
       }); 
      }); 
      socket.on('addPlus', function(msg){ 
       // save the comment 
       Question.findOne({_id: msg.question}, function(err, question){ 
        if (err) throw err; 
        question.plus = question.plus + 1; 
        question.save(function(err) { 
         if (err) throw err; 
         io.to(msg.room).emit("addPlus", question); 
        }); 
       }); 
      }); 
      socket.on('addMinus', function(msg){ 
       // save the comment 
       Question.findOne({_id: msg.question}, function(err, question){ 
        if (err) throw err; 
        question.minus = question.minus + 1; 
        question.save(function(err) { 
         if (err) throw err; 
         io.to(msg.room).emit("addMinus", question); 
        }); 
       }); 
      }); 
     }); 
    } 

    return{ 
     setup: setup 
    } 
} 

module.exports = new RoomService(); 

질문 목록을 반환 할 때 주석 배열을 채우려고합니다. Mongoose에서 populate 메서드로 시도했지만 주석 배열이 반환됩니다.

[{"title": "test", "comments": ["1253454", "654654747"]}, 
{"title": "test", "comments": ["1253454", "654654747"]}] 

그러나 나는 이런 식으로 뭔가 원하는 : 내가 잘못

[{"title": "test", "comments": [{"comment": "test"}, {"comment": "test2"}]}, 
{"title": "test", "comments": [{"comment": "test"}, {"comment": "test2"}]}] 

를하고있는 중이 야 무엇을

Question.find({}).populate("comments") 
        .exec(function(err, questions) { 

         socket.emit("questions", questions) 
       }); 

나는 이런 식으로 뭔가를 얻을 수 채우기 방법을 넣어하지 않는 경우?

+0

, 당신은이처럼 지정 않았다'mongoose.model ('코멘트' , CommentSchema); QuestionSchema의'ref' 부분은 중요합니다. – CreasolDev

+0

CommentSchema 앞에 QuestionSchema를 선언하는 것과 관련이 있습니다. 몽구스 API는 스키마 생성자 부분에'Note'를 가지고 있습니다 : http://mongoosejs.com/docs/api.html#schema_Schema – CreasolDev

+0

이 두 스키마를 어떻게 export했는지 보여줄 수 있습니까? 어쩌면'ref'가 스키마를 내보내는 데 사용되는 적절한 이름을 얻지 못했을 수도 있습니다. –

답변

0

당신의 몽구스 버전은 무엇입니까? 버전 4.7.1 나를 위해 괜찮 :

import { connDb } from './base'; 
import { model, Schema, SchemaTypes, disconnect } from 'mongoose'; 

const Question = model<any>('Question', new Schema({ 
    title : SchemaTypes.String, 
    comments: [ 
    { 
     type: SchemaTypes.ObjectId, 
     ref : 'Comment', 
    }, 
    ], 
})) 
const Comment = model<any>('Comment', new Schema({ 
    comment: SchemaTypes.String, 
})) 

connDb().then(() => Promise.all([ 
    Comment.remove({}), 
    Question.remove({}), 
])).then(() => Comment.insertMany([ 
    { 
    comment: 'hello', 
    }, 
    { 
    comment: 'world', 
    } 
])).then((data: any[]) => Question.insertMany([ 
    { 
    title : 'question', 
    comments: data.map((item: any) => item._id), 
    } 
])).then(() => Question.find({}).populate('comments').exec()).then((d) => { 
    console.log(JSON.stringify(d)) 
}).then(() => disconnect()) 

결과는 다음`mongoose.model` 부분에서

+ ts-node ./src/__test__/pop_comment.ts 
[{"_id":"5846322e69db6c1ec86ac5fd","__v":0,"title":"question","comments":[{"_id":"5846322e69db6c1ec86ac5fb","__v":0,"comment":"hello"},{"_id":"5846322e69db6c1ec86ac5fc","__v":0,"comment":"world"}]}] 
+0

몽구스'4.7.0'을 사용하고 있었는데'4.7.1'을 시도했지만 같은 결과를 얻었습니다. – Servietsky

+0

@Servietsky 앱의 전체 코드를 게시 할 수 있습니까? 어쩌면 뭔가 잘못되었습니다 – kcats

+0

질문에 전체 코드를 게시했습니다. 방금 REST API로 부품을 제거했습니다. – Servietsky