gpt4 book ai didi

javascript - Node JS MongoDB 不保存

转载 作者:行者123 更新时间:2023-11-30 16:28:50 24 4
gpt4 key购买 nike

我是 Node JS 的新手,所以我可能遗漏了一些相当明显的东西。我最近一直在尝试使用 Mongoose 将一些数据保存到数据库中,但我的尝试一直没有成功。虽然服务器告诉我它已保存,但我的数据库中没有数据的踪迹。

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;

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': [] } }

谢谢,卡梅伦·琼斯

编辑:只是为了确认,另一次我保存数据时它显示在数据库内部完全没有问题。它只是最后一个起作用的。

最佳答案

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

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

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

接下来,要自动执行所有操作,您将使用upsert(更新或插入)

Edit: removing $set portion

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 has support for $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);

关于javascript - Node JS MongoDB 不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com