在NodeJS中对require的排序似乎会产生错误

时间:2015-12-31 06:21:24

标签: javascript node.js mongodb express

我遇到的问题是我在NodeJS的主server.js文件中需要各种模型。 这是我的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);

这是我的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);

这是主要的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 ///////////////////////////////////////////////////////

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

运行代码时出现的错误是:

/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)

我无法弄清楚我做错了什么。当我在serve.js文件中颠倒var dealer和var Product的顺序时,我得到另一个错误,说明没有定义Product.findOne。

请帮忙!

2 个答案:

答案 0 :(得分:1)

在使用它们之前定义两个模式以消除循环。模式不需要彼此要求。您可以从模型中删除find / findOne调用,并在实例化后调用它们。

看起来您可能正在将产品架构与经销商的findOne相结合,以尝试将经销商数据推送到产品架构。架构不应基于另一个架构的文档而更改。

http://mongoosejs.com/docs/populate.html有一个很好的例子,说明如何使用两个模式来引用其他集合中的文档。这表明它不需要模式相互要求。

更新

我已经找到了一个快速工作的例子。如果mongod在本地运行,这将运行。

server.js

final HttpServletResponse response
long current = System.currentTimeMillis();
long expires = current + 86400000;
response.setHeader("Cache-Control", "no-transform, max-age="+ 86400 + ", public");
response.addDateHeader("Expires", expires);
response.addDateHeader("Last-Modified", current);

product.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);
                        }
                    });
                }
            });
        });

    });
});

dealer.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);

运行上面的控制台以进行节点打印:

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);

希望这有助于朝着正确的方向前进。我把所有东西嵌套在这里以保持简单。使用promises,生成器或单独的函数调用可能会更好。

答案 1 :(得分:0)

尝试:

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

而不是:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:name="com.example.sybilnaushad.mapdemo.MapsActivity"
 />