Mongoose 如何对不同的集合使用相同的架构,但仍然能够单独更新这些集合

2024-01-17

我在 comments.model 文件中声明了 2 个集合:

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

var currentDate = new Date().getDate();
var currentMonth = new Date().getMonth()+1;
var currentYear = new Date().getFullYear();

var battleFieldOneCommentsSchema = new Schema( {
    user_name: {type: String},
    comment: {type: String},
    date_created: {type: String, default: String(currentDate+"/"+currentMonth+"/"+currentYear)},
    likes: {type: Number, default: 0},
    dislikes: {type: Number, default: 0}
});


module.exports = mongoose.model('battlefieldOne_Comments', battleFieldOneCommentsSchema);
module.exports = mongoose.model('another_game_Comments', battleFieldOneCommentsSchema);

我有一个 index.js 文件,其中包含用于将注释插入数据库的 API:

var battlefieldOne_Comments = require('../models/comments');
var anotherGame_Comments = require('../models/comments');

router.post('/add_battlefieldOne_Comment', function(req, res, next) {
    comment = new battlefieldOne_Comments(req.body);
    comment.save(function (err, savedComment) {
        if (err)
            throw err;

        res.json({
            "id": savedComment._id
        });
    });
});

router.post('/add_anotherGame_Comments', function(req, res, next) {
    comment = new anotherGame_Comments(req.body);
    comment.save(function (err, savedComment) {
        if (err)
            throw err;

        res.json({
            "id": savedComment._id
        });
    });
});

module.exports = router;

当我使用该 API 时,它会将相同的注释插入到数据库上的两个集合中。我知道这是因为 index.js 文件中的两个注释变量需要相同的文件。有没有办法解决这个问题,因为我不想为每个模式创建一个新的模型文件。我是 Nodejs 和 mongoose 的新手,所以这可能是一个愚蠢的问题,但是有没有一种方法可以定义单个模式并将该模式​​用于许多集合,同时仍然能够单独且独立地更新这些集合?


您导出和要求模型的方式index.js不会达到你想要的效果。

当你使用module.exports就像你没有给出要导出的值的名称,所以当require在该文件上调用,您最终将需要两个变量具有相同的值。

您想要在这里做的是将模型设置为不同的变量,然后导出这些变量:

var battlefieldOneComments = mongoose.model('battlefieldOne_Comments', battleFieldOneCommentsSchema);
var anotherGameComments = mongoose.model('another_game_Comments', battleFieldOneCommentsSchema);
module.exports = {
    battlefieldOneComments : battlefieldOneComments,
    anotherGameComments : anotherGameComments
} 

之后,您可以通过访问中的内容来需要它们index.js:

var battlefieldOne_Comments = require('../models/comments').battlefieldOneComments;
var anotherGame_Comments = require('../models/comments').anotherGameComments;

这样,您不需要两个变量使用相同的模型,并且它应该保存您对不同集合的评论。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose 如何对不同的集合使用相同的架构,但仍然能够单独更新这些集合 的相关文章

随机推荐