[英]Setting Mongoose collection name
我為此感到震驚。 我想將集合名稱傳遞給Mongoose Schema對象實例的模型構造函數。
let mongoose = require('mongoose'),
Schema = mongoose.Schema;
let schema = new Schema({
name: {type: String}
}, { collection: 'testing' });
module.exports = mongoose.model("Item", schema);
通過使用如上所述的collection參數,我可以將其從項目更改為測試。 我也嘗試過通過對象上的方法設置屬性。 如在預保存的掛鈎中所示,它可以正確設置它。 但是實例仍使用原始集合名稱。 我想從調用代碼中傳遞集合名稱。
let schema = require(path.join(__rel__, __models__, "schema"));
let item = new schema(itemObject);
item.save(function(err, item) {});
我想通過某種方式為該對象傳遞新的集合名稱。
我已將架構修改為:
module.exports = function(collectionName) {
return mongoose.model("Item", ItemSchema, collectionName);
};
並這樣稱呼:
Item = require(path.join(__rel__, __models__, "ItemSchema"))
("the_collection_name")
效果很好。
我聲明了如下的架構
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const marksSchema = new Schema({
username: String,
year: Number,
section: String,
week: Number,
marks: [{
qid: String,
questionName: String,
marksScored: Number,
isAttempted: Boolean
}],
quizmarks:Number,
});
module.exports = mongoose.model('marks', marksSchema, 'marks');
並在server.js中將其引用如下
const Marks = require('../models/Marks');
models是包含我所有模式的文件夾,它是server.js之外的目錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.