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

标签 javascript node.js mongodb

我在 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 的新手,所以这可能是一个愚蠢的问题,但是有没有一种方法可以定义单个模式并将该模式​​用于许多集合,同时仍然能够单独且独立地更新这些集合? p>

最佳答案

您在 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;

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

关于javascript - Mongoose 如何对不同的集合使用相同的架构,但仍然能够单独更新这些集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751908/

相关文章:

node.js - 将文档 ID 作为字段 ID 包含在 firestore 中

node.js - Node 检查器调试

php - 安装 Mongo

javascript - 如何在函数调用期间实现可选括号? (函数重载)

javascript - Jquery .getJSON 和 ASP.NET MVC

javascript - 如何: Stackoverflow/Twitter JS dialogue box

node.js - 使用Webpack打包ES6模块

javascript - 我可以在reactjs中的类之外声明一个全局变量吗

mongodb - filter:= bson.D {{“hello”,“world”}}}而不是使用value(world)如何传递包含该值的变量(world)

javascript - 限制下载次数