0

项目的结构是

结构体

主文件是位于主目录中的 index.js。这个有

'use strict'

var mongoose = require('mongoose');
var app = require('./app');

var port = process.env.port || 3000;

mongoose.connect('mongodb://localhost:27017/changeProducts',(err,res) =>{
    if(err){
        throw err;
    }else{
        console.log("Base de datos funcionando correctamente..");

        app.listen(port, function(){
            console.log('Servidor nodejs corriendo(app.listen)... ');
        });

    }
});

猫鼬的版本是5.0

app.js 是

'use strict'

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

//carga de rutas
//cr
var roleRoutes = require('./routes/cr/role');
var userRoutes = require('./routes/cr/user');
var loginRoutes = require('./routes/cr/login');
//category
var categoryRoutes = require('./routes/cr/category');

//publication
var publicationRoutes = require('./routes/publication/publication');
var offerRoutes = require('./routes/publication/offer');



app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());

//configurar cabeceras
app.use((req, res, next)=>{
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-API-KEY, Origin, X-Requested-With','Content-Type, Accept, Access-Control-Request-Method');
    res.header('Access-Control-Allow-Method', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');

    next();
});


//rutas base
//cr
app.use('/api', roleRoutes);
app.use('/api', userRoutes);
app.use('/api', loginRoutes);
app.use('/api', categoryRoutes);

//publication
app.use('/api', publicationRoutes);
app.use('/api', offerRoutes);


module.exports = app;

像 userRoutes 这样的路由在文件夹路由中。

第一条路线是 routes/cr/category.js

'use strict'

var express = require('express');
var CategoryController = require('../../controllers/cr/category');
var api = express.Router();
var middlewareSecurity = require('../../security/middleware');

api.get('/categories', CategoryController.getCategories );

module.exports = api;

另一个是 routes/cr/user.js

'use strict'

var express = require('express');
var UserController = require('../../controllers/cr/user');
var api = express.Router();
var middlewareSecurity = require('../../security/middleware');

//api.get('/users/',middlewareSecurity.HasRole("admin,user"), UserController.getUsers );

//actions of user
api.get('/users/', UserController.getUsers);
api.get('/user/:id', UserController.getUser);
api.post('/user', UserController.saveUser);
api.put('/user/:id', UserController.updateUser);
api.delete('/user/:id', UserController.deleteUser);

module.exports = api;

模式在 models/cr

位于“models/category.js”中的第一个模式是

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CategorySchema = Schema({
    name: String,
    subcategories: [{
        name: String
    }]
});

module.exports = mongoose.model('Category',CategorySchema);

另一个 Schema 是 UserSchema,它看起来像这样

 'use strict'

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;


    var UserSchema = Schema({
        firstName: {
            type: String,
            required: true
        },
        secondName: String,
        lastName: {
            type: String,
            required: true
        },
        email: {
            type: String,
            unique: true,
            required: true
        },
        password: {
            type: String,
            required: true
        },
        status: {
            type: String,
            required: true
        },
        roles: [{
            type: Schema.ObjectId,
            ref: 'Role'
        }],

        publications: [{
            title: {
                type: String,

            },
            description: String,
            status: {
                type: String,

            },
            createdAt: {
                type: Date
            },
            updatedAt: {
                type: Date,
                default: Date.now()
            },

            pictures: [{
                name: String
            }],

            categories: [{
                type: Schema.Types.ObjectId,
                refPath: 'Category'
            }],

            publicationOffers: [{
                idpublication: [{
                    type: Schema.ObjectId,
                    ref: 'User.publications'
                }],
                iduser: {
                    type: Schema.ObjectId,
                    ref: 'User'
                },
                createdAt: {
                    type: Date
                }
            }]
        }]
    });


    module.exports = mongoose.model('User', UserSchema);

我有一个名为 mongooseeder mongooseeder的插件

为了开始我在终端运行

节点种子。

这会创建一些类别数据。

在我跑之后

npm start(记得用 npm install 安装依赖)

文件 controllers/cr/user.js 有

'use strict'

var User = require('../../models/cr/user');
var bcrypt = require('bcrypt');
var path = require('path');
var fs = require('fs');

其中一个功能是

   function getUsers(req, res) {

        var find = User.find({}).sort('-firstName');

        find.exec((err, users) => {
            if (err) {
                res.status(500).send({
                    message: "Error en la peticion"
                });
                return;
            }

            if (!users) {
                res.status(404).send({
                    message: "no hay users"
                });
                return;
            }

            User.populate(users, {
                path: 'publications.categories'
            }, (err, users) => {

                if (err) {
                    res.status(500).send({
                        message: "Error en la peticion"
                    });
                    return;
                }

                if (!users) {
                    res.status(404).send({
                        message: "User no encontrado"
                    });
                    return;
                }


                res.status(200).send({
                    users
                });


                // var options = {
                //     path: 'publications.categories',
                //     select: 'subcategories.name'
                // };

                // if (err) {
                //     res.status(200).send({
                //         users
                //     });
                // }
                // User.populate(users, options, function (err, users) {
                //     res.status(200).send({
                //         users
                //     });
                // });

            });
        });
    }

module.exports = {
    getUser,
    getUsers,
    saveUser,
    updateUser,
    deleteUser
}

此方法由 routes/cr/user.js 使用 this contains(查看描述路径在哪里以及包含的内容) api.get('/users/', UserController.getUsers);

链接http://localhost:3000/api/users显示了这个

{
    "users": [
        {
            "roles": [
                "5ae4a8b0a7510e3bd80917d5"
            ],
            "publications": [],
            "_id": "5ae79ee4b34bea810861ccc5",
            "firstName": "santiago4",
            "lastName": "torres3",
            "email": "santiago5020g@hotmail.com4",
            "status": "activo",
            "password": "$2b$10$rONv8dlZVOMJ4kU1x4XUmuVeTiyl.B.IVrIIlPDHz.0Yuqh5w05wK",
            "__v": 0
        },
        {
            "roles": [],
            "publications": [
                {
                    "updatedAt": "2018-04-30T03:23:11.921Z",
                    "categories": [
                        "5ae4a8b0a7510e3bd80917db",
                        "5ae4a8b0a7510e3bd80917da"
                    ],
                    "pictures": [],
                    "publicationOffers": [],
                    "_id": "5ae68cbf7cda345ec0b910f3",
                    "title": "publicacio2",
                    "description": "descripcion2",
                    "status": "activo",
                    "createdAt": "2018-04-30T03:25:51.053Z"
                },
                {
                    "updatedAt": "2018-04-30T03:45:14.159Z",
                    "categories": [
                        "5ae4a8b0a7510e3bd80917db"
                    ],
                    "pictures": [],
                    "publicationOffers": [],
                    "_id": "5ae692183670e54b9c529698",
                    "title": "publicacio2",
                    "description": "descripcion2",
                    "status": "activo",
                    "createdAt": "2018-04-30T03:48:40.654Z"
                },
                {
                    "updatedAt": "2018-04-30T04:01:23.131Z",
                    "categories": [
                        "5ae4a8b0a7510e3bd80917db"
                    ],
                    "pictures": [],
                    "publicationOffers": [],
                    "_id": "5ae6956d9e15516ccceb13d8",
                    "title": "publicacio2",
                    "description": "descripcion2",
                    "status": "activo",
                    "createdAt": "2018-04-30T04:02:53.177Z"
                }
            ],
            "_id": "5ae689f9a67a6284f4af4033",
            "firstName": "santiago3",
            "lastName": "torres3",
            "email": "santiago5020g@hotmail.com3",
            "status": "activo",
            "password": "$2b$10$ge1lS.r/eV1nJRkQDi4dn.0AQKpJfI.a5GzBlpsN5trHefVRVjVCS",
            "__v": 0
        },
        {
            "roles": [],
            "publications": [],
            "_id": "5ae689f0a67a6284f4af4032",
            "firstName": "santiago2",
            "lastName": "torres2",
            "email": "santiago5020g@hotmail.com2",
            "status": "activo",
            "password": "$2b$10$HND7lixmr5RT4A/Kz5gv6.it9kmHpauytIHw/UydgTOAwkbNTJf8O",
            "__v": 0
        },
        {
            "roles": [],
            "publications": [],
            "_id": "5ae689e5a67a6284f4af4031",
            "firstName": "santiago1",
            "lastName": "torres1",
            "email": "santiago5020g@hotmail.com1",
            "status": "activo",
            "password": "$2b$10$.sNgBlSerC6f19Hd2.xnzOtpUAd8BB9JXXM5BlGIvr0dUhWOtn5IS",
            "__v": 0
        }
    ]
}

文件 controllers/cr/category.js 有

'use strict'

var Categories = require('../../models/cr/category');


function getCategories(req, res){

    Categories.find({},(err, categories) =>{
        if(err){
            res.status(500).send({ message: 'Error en la peticion' });
            return;   
        }

        if(!categories){
            res.status(404).send({ message: 'No hay categories' });
            return
        }

        res.status(200).send({ categories });
    });
}


module.exports = {
    getCategories
}

此方法由 routes/cr/category.js 使用 this contains(查看描述路径在哪里以及包含的内容)

'use strict'

var express = require('express');
var CategoryController = require('../../controllers/cr/category');
var api = express.Router();
var middlewareSecurity = require('../../security/middleware');

api.get('/categories', CategoryController.getCategories );

module.exports = api;

http://localhost:3000/api/categories将显示此 json

{
    "categories": [
        {
            "subcategories": [
                {
                    "_id": "5ae4a8b0a7510e3bd80917db",
                    "name": "Decoracion"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917da",
                    "name": "Electrodomésticos"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917d9",
                    "name": "Cocina"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917d8",
                    "name": "Muebles"
                }
            ],
            "_id": "5ae4a8b0a7510e3bd80917d7",
            "name": "Hogar",
            "__v": 0
        },
        {
            "subcategories": [
                {
                    "_id": "5ae4a8b0a7510e3bd80917e0",
                    "name": "Computador escritorio"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917df",
                    "name": "Laptop"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917de",
                    "name": "Celulares"
                },
                {
                    "_id": "5ae4a8b0a7510e3bd80917dd",
                    "name": "Tablets"
                }
            ],
            "_id": "5ae4a8b0a7510e3bd80917dc",
            "name": "Tecnología",
            "__v": 0
        }
    ]
}

我需要填充引用 CategorySchema 子类别的 UserSchema 类别(参见前面提到的模式)。如果您在文件 controllers/cr/user.js 中看到

User.populate(users, {
            path: 'publications.categories'
        }, (err, users) => {....

目前 UserSchema 包含这个

categories: [{
                type: Schema.Types.ObjectId,
                refPath: 'Category'
            }],

我正在尝试做这样的事情

 categories: [{
                type: Schema.Types.ObjectId,
                refPath: 'Category.subcategories'
            }],

类别在出版物中(参见前面提到的模式)

我需要得到这样的东西

"publications": [
                {
                    ...
                    "categories": [
                        {
                          "_id": "5ae4a8b0a7510e3bd80917db",
                          "name": "subcategory1"
                        },
                        {
                           "_id": "5ae4a8b0a7510e3bd80917da",
                           "name": "subcategory2"
                        }
                    ]

                },
                {
                    ....
                    "categories": [
                        {
                           "_id": "5ae4a8b0a7510e3bd80917e0",
                           "name": "subcategory1"
                        }
                    ]                
                },
    ]

但它在 UserSchema 的出版物中向我展示了这一点

"publications": [
            {
                ...
                "categories": [
                    "5ae4a8b0a7510e3bd80917db",
                    "5ae4a8b0a7510e3bd80917da"
                ]

            },
            {
                ...
                "categories": [
                    "5ae4a8b0a7510e3bd80917e0"
                ]                
            },
]

出版物是 UserSchema 的 inisde(参见前面提到的 UserSchema)

这是下载repository的链接repository的项目 链接在哪里

请帮我解决这个问题。我一直在寻找和尝试很多事情,但都没有成功。我在文档、stackoverflow 和其他网站中找不到解决方案。没有任何效果。我尝试使用猫鼬的动态引用,但这不起作用。我试着用这个。 https://github.com/buunguyen/mongoose-deep-populate

我尝试了很多东西,但都没有奏效。请帮我!。我很担心。

4

0 回答 0