从猫鼬创建和获取索引

时间:2020-05-06 15:58:03

标签: javascript node.js mongodb mongoose

我正在尝试在数据库中创建条目并给他们一个号码。对于每个 new 条目,我想为其分配一个唯一的索引号,然后在json中解析该索引号。但是,我在Mongoose文档中可以找到的是,您可以拥有Mongoose创建索引,可以在MongoDB中调用createIndex函数。我如何查看该索引并返回它?如何使索引从0到无穷大?


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

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

const dns = require('dns');

var mongo = require('mongodb');
var mongoose = require('mongoose');

var cors = require('cors');

// Basic Configuration 
var port = process.env.PORT || 3000;
process.env.DB_URI='/MY DATABASE'

mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }).
catch(error => handleError(error));

mongoose.connection.on('error', err => {
  console.log(err);
});

app.use(cors());


  //First we create an URL schema and Model in MongoDB.
  const urlSchema = new mongoose.Schema({ 
  original_url: String,
  short_url: {type: Number, index: 'hashed'}
  })


  const urlModel = mongoose.model('urlModel', urlSchema);

app.post('/PATH', function(req, res, done) {


  //Now we check if the url was actually valid. 
  //If it's valid we will start creating a model in the DB.
  if(/(^https:\/\/)/.test(req.body.url) || /(^http:\/\/)/.test(req.body.url)) {
    var userUrl = req.body.url;
    var urlNumber = 0;

    var input = new urlModel({
      original_url: userUrl
    });

  //Check if the url was already added to the database and return a new or updated item.
      var query = {'original_url': userUrl };

      urlModel.findOneAndUpdate(query, {'original_url': userUrl}, {new: true, upsert: true}, function(err, updated) {
      if (err) return res.send(500, {error: err});
      var result = {'original_url': updated.original_url}
      res.json(result);
      });


    input.save(function(err, data) {
      if (err) return console.log('Save gave an error: ' + err);
      done(null, data);
    });
  }

  //If url wasn't valid
  else {
    res.json({error: "Invalid url"});
  }
});

0 个答案:

没有答案