Nodejs 如何使用mongoose存入内嵌文档

Nodejs 如何使用mongoose存入内嵌文档

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不行,请教各位!


6 回复

好的,我们来解决如何在 Node.js 中使用 Mongoose 存储内嵌文档的问题。具体来说,我们将通过修改现有的代码,展示如何正确地存储 reprint_info 字段。

首先,我们需要确保 reprint_info 字段被正确地定义为一个内嵌文档(Embedded Document)。然后,在保存数据时,确保这个内嵌文档也被正确地设置。

下面是修改后的代码:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db'); // 连接到本地 MongoDB 数据库

var Schema = mongoose.Schema;

// 定义 Article 模型
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;

// 定义 Article 文档的 schema
var articleSchema = new Schema({
    name: String,
    head: String,
    time: {
        date: Date,
        year: Number,
        month: String,
        day: String,
        minute: String
    },
    title: String,
    tags: [String],
    zhengwen: String,
    comments: [String], // 假设评论也是字符串数组
    reprint_info: { // 内嵌文档
        source: String,
        author: String
    },
    pv: Number
}, {
    collection: 'articles'
});

// 创建模型
var articleModel = mongoose.model('Article', 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: { // 设置内嵌文档
            source: "source_url",
            author: "author_name"
        },
        pv: 0
    };

    var newArticle = new articleModel(article);

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

// 示例用法
var article = new Article("Name", "Head", "Title", ["tag1", "tag2"], "Content");
article.save(function (err, savedArticle) {
    if (err) {
        console.log("Error saving article:", err);
    } else {
        console.log("Article saved successfully:", savedArticle);
    }
});

解释

  1. 定义内嵌文档reprint_info 字段现在是一个对象,包含两个属性:sourceauthor
  2. 保存方法:在 save 方法中,reprint_info 字段被正确地设置为一个对象,并且在创建新的 articleModel 实例时传递给构造函数。
  3. 示例用法:最后提供了一个示例,展示了如何创建一个新的 Article 实例并保存它到数据库中。

这样,你就可以将内嵌文档 reprint_info 正确地存储到 MongoDB 中了。


//创建内嵌文档 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.

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

对于你提到的问题,主要是在保存 reprint_info 字段时遇到问题。根据你的描述和提供的代码,似乎 reprint_info 字段无法正确存储到 MongoDB 中。

在你的 articleSchema 中,reprint_info 字段被定义为 Schema.Types.Mixed 类型,这意味着它可以存储任意类型的 JSON 数据。问题可能在于你在创建 article 对象时没有正确设置 reprint_info 字段。

下面是修正后的代码示例:

var mongoose = require('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: {}, // 确保这里正确设置了 reprinted_info 字段
        pv: 0
    }

    var newArticle = new articleModel(article);

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

在这个示例中,我确保了 reprint_info 字段被正确地初始化为空对象 {}。这样就可以确保它能被正确存储到 MongoDB 中。

如果仍然存在问题,请检查是否有其他逻辑错误或数据验证规则阻止了 reprint_info 字段的存储。

回到顶部