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

  • 本文关键字:集合 单独 更新 javascript node.js mongodb
  • 更新时间 :
  • 英文 :


我有 2 个集合,我在评论中声明了.model 文件:

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);

我有一个索引.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 时,它会将相同的注释插入到数据库的两个集合中。我知道这是因为索引.js文件中的两个注释变量都需要同一个文件。有没有办法解决这个问题,因为我不想为每个架构创建一个新的模型文件。我是nodejs和猫鼬的新手,所以这可能是一个愚蠢的问题,但是有没有办法定义单个模式并将该模式用于许多集合,同时仍然能够单独和独立地更新这些集合?

导出和要求模型在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;

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

相关内容

最新更新