Javascript Mongoose如何对不同的集合使用相同的模式,但仍然能够单独更新这些集合
我在comments.model文件中声明了两个集合:Javascript Mongoose如何对不同的集合使用相同的模式,但仍然能够单独更新这些集合,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我在comments.model文件中声明了两个集合: var mongoose=require('mongoose'); var Schema=mongoose.Schema; 要求('./util'); var currentDate=新日期().getDate(); var currentMonth=新日期().getMonth()+1; var currentYear=新日期().getFullYear(); var battleFieldOneCommentsSchema=新模式({
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
要求('./util');
var currentDate=新日期().getDate();
var currentMonth=新日期().getMonth()+1;
var currentYear=新日期().getFullYear();
var battleFieldOneCommentsSchema=新模式({
用户名:{type:String},
注释:{type:String},
创建日期:{type:String,默认值:String(currentDate+“/”+currentMonth+“/”+currentYear)},
喜欢:{type:Number,默认值:0},
不喜欢:{type:Number,默认值:0}
});
module.exports=mongoose.model('battlefieldOne_Comments',battlefieldOne commentschema);
module.exports=mongoose.model(‘另一场比赛’评论),battlefieldonecommentschema)代码>在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;
这样,您就不需要两个变量都使用同一个模型,它应该将您的注释保存在不同的集合上。尝试将您的模型设置为变量,然后将其导出。i、 e:var bfonecoments=mongoose.model('battlefieldOne_Comments'…
,然后module.exports={bfonecoments:bfonecoments}
现在需要它们,您可以使用require('../models/Comments').bfonecoments;
。