节点JS MongoDB不保存

时间:2015-11-12 03:24:22

标签: javascript node.js mongodb debugging asynchronous

我是Node JS的新手,所以我可能会遗漏一些相当明显的东西。我最近一直试图将一些数据保存到带有猫鼬的数据库,但我的尝试都没有成功。虽然服务器告诉我它已保存,但我的数据库中没有数据跟踪。

app.js(底部附近代码的相关部分)

/* REQUIRES */
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var moment = require('moment');
var app = express();
var router = express.Router();
var port = 80;
moment().format();

/* MONGOOSE CONNECT & MODEL */
mongoose.connect('mongodb://127.0.0.1:27017/giveaway');
var Giveaway = require('./models/giveaway');
var Entry = require('./models/entry');

/* EXPRESS APP LISTEN */
app.listen(port, function() {
  console.log('Magic happens on port %s.', port);
});

/* VIEW ENGINE, MIDDLEWARE SETUP, AND STATIC FILES */
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));

router.get('/:giveawayId', function(req, res, next) {
  var giveawayId = req.params.giveawayId;
  Giveaway.find({ _id: giveawayId }, function(err, giveaway) {
    if (err) throw err;
    if (Object.keys(giveaway).length < 1) {
      /* NO GIVEAWAY WITH THAT TITLE */
      console.log("error");
      next();
    } else {
      res.render('pages/giveaway', { giveaway: giveaway });
    }
  });
});

router.post('/:giveawayId/enter', function(req, res, next) {
  var giveawayId = req.params.giveawayId;
  var name = req.body.name;
  var email = req.body.email;
  if (name !== "" && email !== "") {
    Entry.findOne({ email: email }, function(err, entry) {
      if (err) throw err;
      if (entry !== null) {
        /* ALREADY ENTERED */
        console.log("error");
        console.dir(entry);
        next();
      } else {
        console.log("success");
          var newEntry = new Entry({
            name: name,
            email: email,
            giveaway: giveawayId
          });
          newEntry.save(function(err) { //PROBLEM IS HERE WHERE IT SAVES THE DATA
            if (err) throw err;
            res.redirect('/' + giveawayId);
          });
      }
    });
  }
});

app.use('/', router);

entry.js(相关模型)

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var entrySchema = new Schema({
  name: String,
  email: String,
  giveaway: String,
  dateEntered: Date,
  winner: {
    type: Boolean,
    'default': false
  }
});

entrySchema.pre('save', function(next) {
  if (!this.dateEntered) {
    this.dateEntered = new Date;
  }
  next();
});

var Entry = mongoose.model('Entry', entrySchema);
module.exports = Entry;

将{enterer保存到db的app.js底部附近的代码放在问题所在的位置。我假设它是某种我忽略的异步错误,但所有的帮助将不胜感激。另一条可能有用的信息是输入变量的输出。即使数据没有显示在数据库中,它也会显示为查询的结果。

error
model {
  '$__': 
   InternalCache {
     strictMode: true,
     selected: undefined,
     shardval: undefined,
     saveError: undefined,
     validationError: undefined,
     adhocPaths: undefined,
     removing: undefined,
     inserting: undefined,
     version: undefined,
     getters: {},
     _id: undefined,
     populate: undefined,
     populated: undefined,
     wasPopulated: false,
     scope: undefined,
     activePaths: StateMachine { paths: [Object], states: [Object], stateNames: [Object] },
     ownerDocument: undefined,
     fullPath: undefined,
     emitter: EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 } },
  isNew: false,
  errors: undefined,
  _doc: 
   { __v: 0,
     giveaway: 'NyX2sanGx',
     email: 'test',
     name: 'test',
     dateEntered: Wed Nov 11 2015 19:13:50 GMT-0800 (PST),
     _id: ObjectID { _bsontype: 'ObjectID', id: 'VD\u0003î½åwÑ89ì' } },
  '$__original_save': { [Function] numAsyncPres: 1 },
  save: [Function: wrappedPointCut],
  _pres: { '$__original_save': [ [Object], [Object], [Object] ] },
  _posts: { '$__original_save': [] } }

谢谢, 卡梅伦琼斯

编辑:只是为了确认,另一次我保存数据显示在数据库内部没有任何问题。这只是最后一个表现出来的。

1 个答案:

答案 0 :(得分:1)

将Mongoose暂时放在一边,让我们先尝试在Mongo上建模。

您的目标是每个赠品允许1个电子邮件条目,因此您首先要创建唯一索引:

db.entry.ensureIndex({email:1, giveaway:1}, {unique:true});

接下来,要执行原子的所有操作,您可以使用upsert(更新或插入)

  

编辑:删除$ set部分

db.entry.update({
    email: 'me@me.com',
    giveaway: 1
}, {
    $setOnInsert: {
        name: 'John',
        email: 'me@me.com',
        giveaway: 1,
        created: ISODate()
    }
}, {
    upsert: true
});

这意味着:尝试查找具有电子邮件me@me.com和赠品1的用户,如果找不到,则创建包含姓名,电子邮件,赠品,创建和修改日期的新条目。

查看您的记录:

db.entry.findOne()

{
    "_id" : ObjectId("56441446e480d6b501bd0a93"),
    "created" : ISODate("2015-11-12T04:23:34.086Z"),
    "email" : "me@me.com",
    "giveaway" : 1,
    "name": "John"
}
  

Mongoose支持$ setOnInsert

var options = {
    upsert: true,
    'new': true,
    setDefaultsOnInsert: true
};
var find = {
    email: 'me@me.com',
    giveaway: 1,
};
var setOnInsert = {
    email: 'me@me.com',
    giveaway: 1,
    name: 'John',
    created: new Date()
};
Entry.findOneAndUpdate(find, {$setOnInsert: setOnInsert}, options);