如何使用mongoose存入内嵌文档
发布于 11 年前 作者 perny 7503 次浏览 最后一次编辑是 8 年前

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:[], <span style=“background:red”>reprint_info:Schema.Types.Mixed,</span> 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:[], <span style=“background:red”>reprint_info:{},</span> pv:0 }

var newArticle = new articleModel(article);

newArticle.save(function(err, theArticle){
    if(err){
        return callback(err);
    }
    callback(null, theArticle);
})

};

其他字段都能顺利存入mongoDB,只有reprint_info不行,请教各位!

4 回复

//创建内嵌文档 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’ }); 这样是可以内嵌文档,但这样是一组内嵌文档,我想要的是一个内嵌文档,怎么解决啊?

你这个示例里面,存的是个空的 reprint_info,

按你原帖的写法,用 Schema.Types.Mixed,然后你随便复制给 reprint_info 比如 {a: 1},然后再存下试试?

看来我还是对NoSQL型数据库没有搞透彻,其实没有必要事先定义全部字段,因为在使用mongodb作为数据库时,向其插入文档的时候可以增加字段!这与传统数据库是不同的

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.

无责任摘自文档 我也顺便学习了 感谢楼主探路

回到顶部