简体   繁体   中英

Cannot overwrite model once compiled

I want to insert records in mongodb using mongoose but i am getting error "cannot overwrite "story" model once compiled"

app.post('/getdata', (req, res, next) => {
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost:27017/mydb');
  var Schema = mongoose.Schema;
  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;

  var personSchema = Schema({
    _id: Schema.Types.ObjectId,
    name: String,
    age: Number,
    stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
  });


  var storySchema = Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Person' },
    title: String,
    fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
  });

  var Story = mongoose.model('Story', storySchema);
  var Person = mongoose.model('Person', personSchema);
  res.send("Om Success");
})

You are initializing mongoose and all the schema everytime someone hits /getdata post endpoint and as you have express app main process will not be terminated until you so that manually or any unhandled error occurs.

So currently in your program, this is the scenario:

First Request to /getdata

  • Your mongoose will be initialized and Story and Person models are registered with mongoose object and this is global so you can use it from anywhere and this is unique too(your error is here).

From second Request to /getdata

  • You already registered Story and Person models with mongodb://localhost:27017/mydb DB so as it needs unique model it will throw an error.

Solution

or if you want to do this in the same file(not recommended for obvious reasons) do something like this

var express = require('express');
var mongoose = require('mongoose');

var app = express();
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/mydb');

var personSchema = Schema({
    _id: Schema.Types.ObjectId,
    name: String,
    age: Number,
    stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});


var storySchema = Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Person' },
    title: String,
    fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);


app.post('/getdata', (req, res, next) => 
{
    res.send("Om Success");
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM