我的代码是这样的:

try {
  mongoose.connect('mongodb://127.0.0.1:27017/fl00ipflop', {useNewUrlParser: true});
} catch (error) {
  console.log(error.message);
}

/* GET users listing. */
router.get('/get', function(req, res, next) {
  var db = mongoose.connection;
  db.on('error', function() {
    console.log("is error");
  });
  db.once('open', function() {
    console.log("is open");
  });
  var user_id = req.param('id');
  var token = req.param('token');
  var geo = req.param('geo');
  res.send(user_id + ' ' + token + ' ' + geo);
});


我在控制台中看不到任何东西。知道我正在运行nodemon,尽管我认为它并没有改变控制台。

我什至在db.once内和下面设置了代码。

  var schema = new mongoose.Schema({ name: 'string', size: 'string' });
  var Tank = mongoose.model('Tank', schema);

  var small = new Tank({ size: 'small' });
  small.save(function (err) {
    if (err) return handleError(err);
    // saved!
  });

  // or

  Tank.create({ size: 'small' }, function (err, small) {
    if (err) return handleError(err);
    // saved!
  });

  // or, for inserting large batches of documents
  Tank.insertMany([{ size: 'small' }], function(err) {

  });


但是找不到插入的任何文档,也没有创建Tank表。

最佳答案

我建立如下所示的连接:

require('dotenv').config();

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');

const userRoute = require('./routes/user'); //create a route

mongoose.connect('mongodb+srv://myusername:' + process.env.MONGODB_PASSWORD + '@myproject-z8wvn.mongodb.net/myproject?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true })

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use('/user', userRoute); //add the route

app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500).json({
        message: error.message
    })
});


然后,我创建了一个server.js文件以使用nodemon启动服务器。

require('dotenv').config();

var http = require('http');
var app = require('./app');

http.createServer(app).listen(process.env.PORT, () => {
  console.log('---------------------------------------');
  console.log('Server is listening now on port ' + process.env.PORT);
  console.log('---------------------------------------');
});


之后,我创建了我的User模式,如下所示:

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    username: String,
    password: String,
    email: String
});

module.exports = mongoose.model('User', userSchema);


最后创建您的路线(我已经创建了一个新文件user.js):

const express = require('express');
const router = express();
const User = require('../models/user');

router.delete('/getAllUsers', checkAccessToken, (req, res, next) => {

//do whatever you want here
console.log("getAllUsers is working! :)");
});


我希望这有帮助。 :)

关于node.js - 使用mongoose连接到mongoDB:既不会触发错误也不会触发它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59456468/

10-10 00:31