我有3个不同架构的文件。用户有很多笔记本和笔记本有很多笔记。架构示例:
UserSchema:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var User = new Schema({
username: { type: String, require: true, index: { unique: true }, trim: true},
password: { type: String, require: true, select: true },
age: { type: Number, min: 0 },
firstname: String,
secondname: String,
token: String,
role: String,
city: String,
rememberMe: Boolean
});
module.exports = mongoose.model('User', User);
NotebookSchema:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Note = require('./note'),
User = require('./user');
var NoteBook = new Schema({
creator: { type:Schema.ObjectId, ref:"User"},
name: String,
description: String
});
NoteBook.methods.getAllNotes = function(cb) {
Note.find({notebook: this}, function(err, noteList){
cb(noteList);
});
};
module.exports = mongoose.model('NoteBook', NoteBook);
NoteSchema:
var mongoose = require(' mongoose'), Schema = mongoose.Schema;
var NoteSchema = new Schema({
notebook: { type: Schema.Types.ObjectId, ref: 'NoteBook'},
name: String,
description: String,
content: String
});
module.exports = mongoose.model('Note', NoteSchema);
我收到请求userId,我需要打包json所有这一行数据。用户使用笔记本和笔记本在一个json中注释。我有点像这样:
function getTree(req,res){
var data = [];
User.findOne({_id: req.body.userId}, function(err, user) {
NoteBook.find({creator: user._id}, function(err, notebookList) {
for (var idx in notebookList) {
Note.find({notebok: notebookList[idx]._id}, function(err, noteList) {
var children = [];
for (var noteIdx in noteList) {
children.push({
'text': noteList[idx].name,
'a_attr' : {
'data-node-type': 'note',
'data-node-id': noteList[idx]._id,
},
});
}
data.push({
'text': notebookList[idx].name,
'a_attr' : {
'data-node-type': 'notebook',
'data-node-id': notebookList[idx]._id,
},
'children': children
});
});
}
res.json({ tree: data });
});
});
}
但它没有用。
答案 0 :(得分:0)
var async = require("async");
function getTree(req, res) {
var data = [];
User.findOne({_id: req.body.userId}, function(err, user) {
NoteBook.find({creator: user._id}, function(err, notebookList) {
async.forEach(notebookList, function(notebook, callback){
Note.find({notebok: notebook._id}, function(err, noteList) {
var children = [];
for (var noteIdx in noteList) {
children.push({
'text': noteList[idx].name,
'a_attr' : {
'data-node-type': 'note',
'data-node-id': noteList[idx]._id,
},
});
}
data.push({
'text': notebookList[idx].name,
'a_attr' : {
'data-node-type': 'notebook',
'data-node-id': notebook._id,
},
'children': children
});
});
}, function(err){
res.json({ tree: data });
});
});
});
}