我在 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/