在此模型中添加更多集合?"/>
如何在此模型中添加更多集合?
我需要添加另一个集合以执行简单的CRUD操作。如果需要,还可以添加更多集合。
const mongoose = require('mongoose');
const schema = mongoose.Schema({
title: String,
description: String,
published: Boolean
},
{
collection: 'Tutorials',
timestamps: true
});
//If you use this app with a front-end that needs id field instead of _id,
// you have to override toJSON method that map default object to a custom object
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
module.exports = mongoose.model('Tutorial', schema);
回答如下:现在了解您的问题实际上是在询问如何对多个集合使用1个架构,您可以尝试以下操作:
如果您的模式如下:
const schema = mongoose.Schema({
title: String,
description: String,
published: Boolean,
timestamps: true
});
然后您可以将导出(在模型的底部)更改为:
var tutorials = mongoose.model('Tutorials', schema);
var users = mongoose.model('Users', schema);
var products = mongoose.model('Products', schema);
module.exports = {
tutorials : tutorials,
users : users,
products: products
}
上面您可以添加自己喜欢的东西。
然后,当涉及到单独访问每个数据库时,您可以像这样导入它们:
var tutorials = require('../models/schema').tutorials;
var users = require('../models/schema').users;
...
更多推荐
如何在此模型中添加更多集合?
发布评论