这是我今天关于Node.js的第二个问题。已经很晚了,在我上床睡觉之前,我想帮助快速整合这个功能。
我有一个小型的Q& A应用程序,我可以在我的浏览页面上从/向MongoDB读取和写入数据。
但是,我想让时间戳或日期()注册自己,并将每个项目实例写入MongoDB。
在视图上,目前只有作者,标题和正文可见。但是当我查询Mongo时,我想要一个单独的属性来列出创建的日期和时间。 (仅限日期)
我已经定义了一个属性" date" :日期,在我的架构中。我假设它会自动添加,但只添加标题,作者和正文。我认为这是因为它们被定义为讨论路线中的val,但我确定。但是,请注意。
这些是我的代码文件:
discussion.js - / routes
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Discussion = require('../models/discussions');
router.get('/', function(req, res, next){
// alle db records uitlussen, op render alldiscussions
var db = req.db;
Discussion.find({},{},function(e,docs){
res.render('all_discussions', {
"all_discussions" : docs
});
console.log(docs);
});
});
router.get('/create', function(req, res, next){
res.render('add_discussion', {title: 'Diskussr'});
});
router.post('/submit', function(req, res) {
//set DB
var db = req.db;
//form vals
var author = req.body.name;
var title = req.body.title;
var body = req.body.body;
//set collection
var collection = db.get('discussions');
//insert
collection.insert({
"author" : author,
"title" : title,
"body" : body
}, function (err, doc) {
if (err) {
res.send("Database submit error");
}
else {
res.location("all_discussions");
res.redirect("all_discussions");
}
});
});
module.exports = router;
add_discussion.jade - / views
extends layout
block content
h1 Start a discussion
p Start a discussion here on #{title} and help eachother out.
p Voeg hier uw vraag in:
form(action="/submit" method="post" name="submit_discussion")
input(id="name", placeholder="Your name" name="name")
br
br
input(id="title", placeholder="Brief summary of your problem." name="title")
br
br
input(id="body", placeholder="Explain your problem." name="body")
br
br
button(type="sumbit" id="submit" value="submit") Submit
br
discussion.js - / models
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//schema discussions
var DiscussionSchema = new Schema({
author: String,
title: String,
body: String,
category: String,
created: Date
},
{ collection : 'discussions' });
// model
var Discussion = mongoose.model('Discussion', DiscussionSchema, 'discussions');
// test functie: aanmaken vraag on load
// var firstDiscussion = new Discussion({author: "Testuser 1", title: "Testvraag via models"});
// console.log(firstDiscussion);
// //vraag saven
// firstDiscussion.save(function (err, firstDiscussion){
// if (err) return console.error(err);
// });
module.exports = Discussion;
答案 0 :(得分:0)
只需为created
字段添加默认值:
//schema discussions
var DiscussionSchema = new Schema({
author: String,
title: String,
body: String,
category: String,
created: { type: Date, default: Date.now }
},
{ collection : 'discussions' });
或者,由于您使用ObjectId作为主键,因此可以按照@adeneo的建议使用getTimestamp()
提取时间戳:
Discussion.find({}, function(e,docs){
docs.forEach(function(doc) {
console.log("created: " + doc._id.getTimestamp());
});
});