能够添加到MongoDB中的数据库但不能添加到mongoose中

时间:2017-06-29 21:31:53

标签: node.js mongodb heroku mongoose

我正在学习猫鼬。我正在this tutorial工作并遇到一个绊脚石,在我的数据库中添加条目,通过Heroku MongoDB运行。我能够添加到现有的集合" test1"当我加载应用程序时,请尝试使用#m;但是在我的Heroku mLab控制台中,当我访问页面时,我没有看到任何添加到任何集合的内容" trywithmongoose"。救命?以下是index.js中的相关代码:

var express = require('express');
var mongoose = require("mongoose");
var mongo = require('mongodb').MongoClient;
app.get("/trywithmongodb", function(request,response){
    response.send("Looking at the /trywithmongodb page"); 

    var configDB = require('./config/database.js'); 
    //add to the database
    mongo.connect(configDB.url , function(err, db) {
        var shorturl = db.collection("test1");
        var date = new Date();
        var newsitejson={original_url: "accessed at", site_number: date.getHours()+":"+date.getMinutes()}
        shorturl.insert(newsitejson)
        db.close()
        })

    });

app.get('/trywithmongoose', function (request, response) {
var configDB = require('./config/database.js'); 
mongoose.connect(configDB.url);
// grab the user model
var User = require('./app/models/user');

// create a new user
var newUser = User({
  name: 'Peter ',
  username: 'peter45',
  password: 'willbehashed',
  admin: true
});

// save the user
newUser.save(function(err) {
  if (err) throw err;
  console.log('User created!');
});

response.send("You are looking at /trywithmongoose");
});

这里是架构的完整文件user.js:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var userSchema = new Schema({
  name: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  admin: Boolean
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;

0 个答案:

没有答案