Dưới đây là một đối tượng theo nghĩa đen tôi đang cố lưu vào MongoDB. Nó được định nghĩa trong tệp app.js là một máy chủ Express. Khi đối tượng được mã hóa cứng trong máy chủ, giả định của tôi là một bản sao mới sẽ được lưu vào DB mỗi khi tôi chạy máy chủ hoặc ít nhất tài liệu sẽ được lưu một lần và ghi đè hoặc để lại không thay đổi khi phát hiện tài liệu mới giống với tài liệu được lưu trên lần chạy máy chủ cuối cùng. Theo kinh ngạc của tôi, không chỉ không có bản sao nào được tạo ra trong MongoDB, nhưng tài liệu không được lưu lại chút nào. Tuy nhiên, bộ sưu tập 'tin tức' đã được tạo ra, như đã được xác minh với bộ sưu tập hiển thị mongo shell. Ngoài ra, tôi không nhận được bất kỳ lỗi nào trong hàm gọi lại. Tôi cũng đã thử Model.create (doc, fn) trong tuyến đường Express '/ news' của tôi, nhưng điều này cũng không hoạt động (tài liệu nên được lưu mỗi khi tuyến đường '/ news' được gọi bởi khách hàng, nhưng nó không phải). Tôi đang thiếu gì?
Vui lòng đọc chú thích của tôi được đánh dấu bằng "< -" để xem những vấn đề khác hoặc hành vi bất ngờ mà tôi gặp phải. Tôi sẽ rất biết ơn nếu bạn có thể giải quyết những người cũng như trong câu trả lời của bạn.Mongoose không lưu dữ liệu vào MongoDB
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, fs = require('fs');
// Defining connection to the database:
var mongoose = require('mongoose').
connect("mongodb://localhost:27017/my-test-db"),
db = mongoose.connection;
var Schema = mongoose.Schema;
var ObjectID = Schema.ObjectId;
// Setting up the debug flag:
mongoose.set('debug, true');
// Logging connection:
db
.on('error', console.error.bind(console, 'DB connection error.'))
.once('open', console.log.bind(console, 'DB Connection established.'));
// Defining MongoDB schemas:
var usr = new Schema({
first: String,
last: String
});
var newsSchema = new Schema({
headline: String,
bd: String,
imgURI: String,
imgThumbURI: String,
imgCaption: String,
addedOn: Date,
addedBy: {
type: ObjectID,
ref: 'usr'
}
// On user action 'save' populate the addedOn and addedBy fields before the news article is actually saved to the DB:
newsSchema.pre('save', function(next){
if(!this.addedOn) this.addedOn = new Date();
if(!this.addedBy) this.addedBy = {first: "admin", last: "admin"};
});
// Indexing important fields:
usr.index({last: 1});
newsSchema.index({headline: 1});
//Adding the News model:
var News = mongoose.model('news', newsSchema);
var nws1 = new News({
headline: "Test news Headline",
bd: "Test news body. Test news body. Test news body. Test news body. Test news body. ",
imgURI: encodeURI("images/news/img.jpg"),
imgThumbURI: encodeURI("images/news/thumbs/img.jpg"),
imgCaption: "Test news image caption.",
addedOn: new Date(),
addedBy: {first: "Admin", last: "Admin"}
});
nws1.save(function(err, news){
if(err) return console.error("Error while saving data to MongoDB: " + err); // <- this gets executed when there's an error
console.error(news); // <- this never gets logged, even if there's no error.
});
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.resolve(__dirname + '/public'));
app.set('view engine', 'html')
.engine('html', function(path, options, fn){
if('finction' == typeof options){
fn = options, options = {};
}
fs.readFile(path, 'utf8', fn);
});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session());
app.use(express.static(path.join(__dirname, 'public')));
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Cảm ơn bạn đã dành thời gian
Trân trọng
Jared
Bạn đang gọi 'mongoose.connect' để kết nối với cơ sở dữ liệu ở đâu đó bên ngoài của mã này? – JohnnyHK
@JohnnyHK Vâng, tôi. Vui lòng xem câu hỏi được cập nhật. Tôi đã bao gồm mã có liên quan. –