如何在此模型中添加更多集合?

编程入门 行业动态 更新时间:2024-10-09 20:24:40

如何<a href=https://www.elefans.com/category/jswz/34/1760116.html style=在此模型中添加更多集合?"/>

如何在此模型中添加更多集合?

我需要添加另一个集合以执行简单的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;
...

更多推荐

如何在此模型中添加更多集合?

本文发布于:2024-05-07 06:27:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在此   模型   更多

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!