var mongoose = require(‘mongoose’);//引用mongoose模块 mongoose.connect(‘mongodb://localhost/db’);//引入一个数据库连接 var Schema = mongoose.Schema;
function Article(name,head,title,tags,zhengwen){ this.name = name; this.head = head; this.title = title; this.tags = tags; this.zhengwen = zhengwen; }
module.exports = Article;
var articleSchema = new Schema({ name:String, head:String, time:{ date:Date, year:Number, month:String, day:String, minute:String }, title:String, tags:[], zhengwen:String, comments:[], reprint_info:Schema.Types.Mixed, pv:Number },{ collection:’articles’ })
var articleModel = mongoose.model('article_Schema’,articleSchema);
//储存一篇文章和相关信息 Article.prototype.save = function(callback){ var date = new Date(); //储存各种时间格式,方便以后扩展 var time = { date:date, year:date.getFullYear(), month:date.getFullYear()+"-“+(date.getMonth()+1), day:date.getFullYear()+”-“+(date.getMonth()+1)+”-“+date.getDate(), minute:date.getFullYear()+”-“+(date.getMonth()+1)+”-“+date.getDate()+” "+date.getHours()+":"+(date.getMinutes() < 10 ? '0’+date.getMinutes() : date.getMinutes()) } //要存入数据库的文档 var article = { name:this.name, head:this.head, time:time, title:this.title, tags:this.tags, zhengwen:this.zhengwen, comments:[], reprint_info:{}, pv:0 }
var newArticle = new articleModel(article);
newArticle.save(function(err, theArticle){
if(err){
return callback(err);
}
callback(null, theArticle);
})
};
其他字段都能顺利存入mongoDB,只有reprint_info不行,请教各位!
//创建内嵌文档 var reprint_info_Schema = new Schema({});
var articleSchema = new Schema({ name:String, head:String, time:{ date:Date, year:Number, month:String, day:String, minute:String }, title:String, tags:[], zhengwen:String, comments:[], reprint_info:[reprint_info_Schema], pv:Number },{ collection:’articles’ }); 这样是可以内嵌文档,但这样是一组内嵌文档,我想要的是一个内嵌文档,怎么解决啊?
Since Schema.Types.Mixed is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To “tell” Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.
无责任摘自文档 我也顺便学习了 感谢楼主探路