Nodejs 用mongoose取回的对象是否能增加属性?

Nodejs 用mongoose取回的对象是否能增加属性?

Comment.findOne({ _id: id }, function (err, comment) {
comment.test = ‘test’;
console.log(err, comment);
});

console的结果中是不会有test字段的 请问用mongoose取回的对象是否能增加属性?

4 回复

当然可以。Mongoose 文档对象是 JavaScript 的普通对象,你可以在它们上面添加属性。但是需要注意的是,这些新增加的属性不会被自动保存到数据库中。如果你希望将新增加的属性保存到数据库,你需要使用 save 方法显式地保存。

以下是一个简单的示例来展示如何向 Mongoose 返回的文档对象添加属性,并且只在内存中显示:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义一个简单的Schema
const CommentSchema = new Schema({
    content: String,
    author: String
});

// 创建模型
const Comment = mongoose.model('Comment', CommentSchema);

// 连接到 MongoDB 数据库
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        // 查找一个评论
        Comment.findOne({ _id: "some-comment-id" }, function (err, comment) {
            if (err) {
                console.error(err);
            } else {
                // 在评论对象上添加一个新的属性
                comment.test = 'test';
                console.log(comment); // 输出结果中会包含新增的属性

                // 如果你想保存这个新属性到数据库,需要调用save方法
                comment.save((err) => {
                    if (err) {
                        console.error(err);
                    } else {
                        console.log("Comment saved with test field");
                    }
                });
            }
        });
    })
    .catch(err => console.error(err));

在这个例子中,我们首先定义了一个简单的 Comment 模型,然后连接到 MongoDB 数据库。接着,我们通过 findOne 方法查找一个评论,并在找到的评论对象上添加了一个名为 test 的新属性。注意,这个新属性只会在内存中存在,除非我们调用 comment.save() 方法将其保存到数据库。

总结来说,你可以向 Mongoose 取回的对象添加属性,但需要确保这些属性被显式地保存到数据库中。


看是個什麼對象了 MongoDB的特性是Schemaless的 Mongoose是個ODM 所以如果你的存取使用Mongoose而且是定義了MongooseSchema那樣的話是添加不了的~ 但是你可以定義成Mixin 然後 再到代碼里動態修改這個Minxi類型的 然後還要通知Mongoose你把什麼改了 <–這種方法不是特別常用,建議樓主還是在設計上把字段都預留好之類的 ===========這裏講個笑話================== 傳說某東的B2C網站的數據庫這樣的 字段A 字段B 字段C 字段D 字段F 每個字段什麼用法文檔里規定,所以隨便用 ============以上只是傳說聽說的一個笑話而已。。。。。===========

非常感谢

测试了几次发现只有在定义Schema时有的字段才可以被修改,而不能事后添加。

我也想在定义的时候是不是先把这些字段定义成默认值为NULL放在那里,如

category_id: {type ObjectId},
category: {type Object, default: null},
title: { type: String },
...

但是好像也很丑,就像很多冗余数据在那里似的,虽然他们是空的…

在使用 Mongoose 取回的对象时,你确实可以为其添加新的属性。但是,这些新增加的属性不会被保存到数据库中,除非你显式地调用 save 方法来保存它们。

以下是一个简单的示例,展示了如何向 Mongoose 返回的文档中添加新属性:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
    content: String,
});

const Comment = mongoose.model('Comment', CommentSchema);

// 查询文档
Comment.findOne({ _id: id }, function (err, comment) {
    if (err) {
        console.error(err);
        return;
    }
    
    // 向返回的文档中添加新的属性
    comment.test = 'test';
    console.log(comment);  // 输出会包含新增的属性
    
    // 若要保存新属性到数据库,需要调用 save 方法
    comment.save(function (err) {
        if (err) {
            console.error(err);
            return;
        }
        console.log('Document updated successfully.');
    });
});

在这个例子中,我们定义了一个 Comment 模型,并查询了一个特定的文档。当获取到该文档后,我们为其添加了一个名为 test 的新属性。虽然在日志输出中可以看到新增的属性,但如果不调用 save 方法,这个属性将不会被保存到数据库中。如果需要保存新增的属性,必须调用 comment.save() 方法。

这样,你就可以理解如何向 Mongoose 返回的对象中添加新的属性,并了解如何保存这些更改。

回到顶部