使用猫鼬设置数据库和收集

时间:2019-11-29 03:56:46

标签: node.js mongodb mongoose

如何使用猫鼬设置数据库和集合?我正在尝试使用猫鼬连接到mongodb地图集数据库。我的数据库称为“ test_db”,集合名称为“ users”,在哪里可以指定该信息?

这是我的shema(data.js):

// /backend/data.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// this will be our data base's data structure 
const DataSchema = new Schema(
  {
    _id: Number,
    name: String,
    password: String
  }
);

// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("users", DataSchema);

这是server.js:

const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');

const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();

// this is our MongoDB database
const dbRoute = 'mongodb+srv://<user>:<password>@cluster0-bmihj.mongodb.net/test?retryWrites=true&w=majority';
  ;

// connects our back end code with the database
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true });

//let db = mongoose.connection;
const db = conn.db('test_db');

var MyModel = mongoose.model('Test', new Schema({ name: String }));

db.once('open', () => console.log('connected to the database'));

// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));


// this is our get method
// this method fetches all available data in our database
router.get('/getData', (req, res) => {
  Data.find((err, data) => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true, data: data });
  });
});

2 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <!-- 
    MSIProductVersion is defined in InstallerSetup.wixproj as 0.0.1 for local desktop builds.  
    You should pass in the MSBuild Property 'MSIProductVersion' to override it during an automated build.
    See http://msdn.microsoft.com/en-us/library/windows/desktop/aa370859%28v=vs.85%29.aspx for information on allowable values.

    The Product@Id attribute (ProductCode Property) will be a random GUID for each build.  This is to support "Major Upgrades" where each install 
    is a seamless uninstall/reinstall.
    -->
    <Product Id="*" Name="MyAppSetup" Language="1033" Version="$(var.MSIProductVersion)" Manufacturer="MyCompany" UpgradeCode="f06ea643-5b60-4672-ae0a-fa4be98b102c">
        <Package InstallerVersion="301" Compressed="yes" InstallScope="perMachine" />
        <MediaTemplate EmbedCab="yes" />

    <!-- Major Upgrade Rule to disallow downgrades -->
        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />

        <!--Common Launch Condition-->
    <!-- Examples at http://wixtoolset.org/documentation/manual/v3/customactions/wixnetfxextension.html -->
        <PropertyRef Id="WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED"/>
        <Condition Message="This application requires .NET Framework 4.8. Please install the .NET Framework then run this installer again.">
            <![CDATA[Installed OR WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED]]>
        </Condition>

        <!-- Include User Interface Experience -->
        <Icon Id="Icon.ico" SourceFile="Resources\Icon.ico"/>
        <Property Id="ARPPRODUCTICON" Value="Icon.ico"></Property>    
    <UIRef Id="UI"/>

    <!-- Include Features and Directories Fragment -->
        <DirectoryRef Id="INSTALLLOCATION"/>

    </Product>
</Wix>

答案 1 :(得分:0)

由于您在Mongoose中使用模型,因此不再需要指定集合名称。默认情况下,由于您正在使用模型,因此Mongodb会为您定义的每个模型自动生成一个集合。因此,由于这一行代码:

const DataSchema = new Schema( { _身份证号码, 名称:字符串, 密码:字符串 } );

//导出新的模式,以便我们可以使用Node.js对其进行修改 module.exports = mongoose.model(“ users”,DataSchema);

在您的test_db数据库中,将自动为您生成一个用户集合。您可以使用Mongoose定义其他数据模式,并享受Mongodb为其自动为每个数据生成一个集合的好处。