简体   繁体   English

NodeJS中require的顺序似乎会产生错误

[英]Ordering of require in NodeJS seems to produce errors

I am having a problem with the order that i require various models in my main server.js file in NodeJS. 我在NodeJS的主要server.js文件中需要各种模型的顺序有问题。 Here is my product.js Product model file: 这是我的product.js产品模型文件:

var mongoose = require("mongoose");

var Dealer      = require("./dealer.js")
var productSchema = new mongoose.Schema({
    title: String,
    price: String,
    dealers: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Dealer"
        }
    ]
});

var Product = mongoose.model("Product", productSchema);

Dealer.findOne({
    name: "Glaze"
}, function(err, dealer){
    Product.findOne({title: "Awesome Metal Towels"}, function(err, product){
        if(err){
            console.log(err);
        } else{
            product.dealers.push(dealer);
            product.save(function(err, data){
                if(err){
                    console.log(err);
                } else{
                    console.log(data);
                }
            })
        }
    });
});

module.exports = mongoose.model("Product", productSchema);

Here is my Dealer.js file that defines the Dealer model: 这是定义Dealer模型的我Dealer.js文件:

var mongoose = require("mongoose");
var Product = require("./product.js")
var dealerSchema = new mongoose.Schema({
    name: String,
    owner: String,
    estd: Number,
    description: String,
    legal: String,
    facilities: String,
    awards: String,
    hours: String,
    turnover: String,
    mode: String,
    employees: String,
    contact: String,
    address: String,
    email: String,
    notes: String,
    website: String,
    products: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Product"
        }
    ]
});


var Dealer = mongoose.model("Dealer", dealerSchema);

Product.find(function(err, data){
    console.log(data);
});

Product.findOne({
    title: "Awesome Metal Towels"
}, function(err, product){
    Dealer.findOne({name: "Glaze"}, function(err, dealer){
        if(err){
            console.log(err);
        } else{
            dealer.products.push(product);
            dealer.save(function(err, data){
                if(err){
                    console.log(err);
                } else{
                    console.log(data);
                }
            })
        }
    });
});


module.exports = mongoose.model("Dealer", dealerSchema);

And here is the main server.js file : 这是主要的server.js文件:

var express     = require("express");
var app         = express();
var bodyParser  = require("body-parser");
// var seedDB      = require("./seeds.js")
var mongoose    = require("mongoose");

// Connecting the models ////////////////////
var Dealer      = require("./models/dealer.js");
var Product     = require("./models/product.js");
var Category    = require("./models/category.js");
var Brand       = require("./models/brand.js");
/////////////////////////////////////////////

app.use(express.static(__dirname + '/public')); 
//Connecting to the database
var uri = process.env.MONGOLAB_URI || '127.0.0.1/flapi';
mongoose.connect(uri);
//////////////////////////////////////////////
//
//Seeding the database 
// seedDB();
//////////////////////

//Body Parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
////////////////////////////////////////////////////

var port = process.env.PORT || 3000;

// CRUD Routes for Products ///////////////////////////////////////////////////////

..................

The error I get while running the code is : 我在运行代码时遇到的错误是:

/home/aayush/fl/models/product.js:16
Dealer.findOne({
       ^

TypeError: Dealer.findOne is not a function
    at Object.<anonymous> (/home/aayush/fl/models/product.js:16:8)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/home/aayush/fl/models/dealer.js:29:15)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/home/aayush/fl/server.js:8:19)

I am not able to figure out what I am doing wrong. 我无法弄清楚我在做什么错。 When I reverse the order of var Dealer and var Product in the serve.js file, I get another error saying that Product.findOne is not defined. 当我反转serve.js文件中的var Dealer和var Product的顺序时,出现另一个错误,指出未定义Product.findOne。

Please help! 请帮忙!

Define both of your schemas prior to using them to eliminate the cycle. 在使用它们来消除周期之前,先定义两个模式。 The schemas do not need to require each other. 架构不需要互相要求。 You can remove the find/findOne calls from the models and call them after they are instantiated. 您可以从模型中删除find / findOne调用,并在实例化之后调用它们。

It looks like you may be combining the product schema with the findOne of the dealers to try to push dealer data to the products schema. 看来您可能正在将产品架构与经销商的findOne组合在一起,以尝试将经销商数据推送到产品架构。 The schema should not change based on the documents for another schema. 该架构不应基于其他架构的文档进行更改。

There is a good example at http://mongoosejs.com/docs/populate.html for how to use two schemas with references to documents in other collections. http://mongoosejs.com/docs/populate.html上有一个很好的示例,说明如何使用两个架构引用其他集合中的文档。 This shows it without requiring the schemas to require one another. 这显示了它,而无需架构相互要求。

Update 更新

I have hooked up a quick working example. 我已经找到了一个快速工作的例子。 This will run if mongod is running locally. 如果mongod在本地运行,它将运行。

server.js server.js

var express     = require("express");
var app         = express();
var bodyParser  = require("body-parser");
var mongoose    = require("mongoose");
var ObjectID = require('mongodb').ObjectID;
var Dealer      = require("./models/dealer.js");
var Product     = require("./models/product.js");
app.use(express.static(__dirname + '/public')); 
mongoose.connect('mongodb://localhost:27017/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  var glaze = new Dealer({
    _id: new ObjectID(),
    name: 'Glaze', 
    owner: 'owner',
    estd: 2010,
    description: 'description',
    legal: 'legal',
    facilities: 'facilities',
    awards: 'awards',
    hours: 'hours',
    turnover: 'turnover',
    mode: 'mode',
    employees: 'employees',
    contact: 'contact',
    address: 'address',
    email: 'email@email.com',
    notes: 'notes',
    website: 'website.com',
  });

    glaze.save(function (err) {
      if (err) {
        console.error('err: ' + err);
      }

      var product1 = new Product({
        title: 'Awesome Metal Towels',
        price: '$17.99',
        dealers: []
      });

      product1.dealers.push(glaze._id);

      product1.save(function (err) {
      if (err) {
            console.error('err: ' + err);
          }
      });

        Product.find(function(err, data){
            console.log('[FIRST]: ' + data);
        });

        Product.findOne({
            title: "Awesome Metal Towels"
        }, function(err, product){
            Dealer.findOne({name: "Glaze"}, function(err, dealer){
                if(err){
                    console.log(err);
                } else{
                    dealer.products.push(product);
                    dealer.save(function(err, data){
                        if(err){
                            console.log(err);
                        } else{
                            console.log('[SECOND]: ' + data);
                        }
                    });
                }
            });
        });

    });
});

product.js product.js

var mongoose = require("mongoose");

var productSchema = new mongoose.Schema({
    title: String,
    price: String,
    dealers: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Dealer"
        }
    ]
});

module.exports = mongoose.model("Product", productSchema);

dealer.js dealer.js

var mongoose = require("mongoose");
var dealerSchema = new mongoose.Schema({
    name: String,
    owner: String,
    estd: Number,
    description: String,
    legal: String,
    facilities: String,
    awards: String,
    hours: String,
    turnover: String,
    mode: String,
    employees: String,
    contact: String,
    address: String,
    email: String,
    notes: String,
    website: String,
    products: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Product"
        }
    ]
});

module.exports = mongoose.model("Dealer", dealerSchema);

Run the above and the console for node prints: 运行以上命令,然后在控制台上打印节点:

[FIRST]: { dealers: [ 5684f0b71e8265a43e3c9c27 ],
  __v: 0,
  price: '$17.99',
  title: 'Awesome Metal Towels',
  _id: 5684f0b71e8265a43e3c9c28 }
[SECOND]: { products: [ 5684f0b71e8265a43e3c9c28 ],
  __v: 1,
  website: 'website.com',
  notes: 'notes',
  email: 'email@email.com',
  address: 'address',
  contact: 'contact',
  employees: 'employees',
  mode: 'mode',
  turnover: 'turnover',
  hours: 'hours',
  awards: 'awards',
  facilities: 'facilities',
  legal: 'legal',
  description: 'description',
  estd: 2010,
  owner: 'owner',
  name: 'Glaze',
  _id: 5684f0b71e8265a43e3c9c27 }

Hopefully this will help get in the right direction. 希望这将有助于朝正确的方向发展。 I nested everything here to keep it simple. 我将所有内容嵌套在这里以使其简单。 You would probably be better off with promises, generators or separate function calls. 使用promise,生成器或单独的函数调用可能会更好。

Try: 尝试:

var Dealer      = require("./dealer")
// ...
var Product = require("./product")

Instead of: 代替:

var Dealer      = require("./dealer.js")
// ...
var Product = require("./product.js")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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