猫鼬中创建新文档时可以添加新属性?

时间:2018-08-28 13:56:35

标签: node.js mongodb mongoose mongoose-schema

我有这个模式(例如):

var WordSchema = new Schema({
    word: {
        type: String
    }
});
module.exports = mongoose.model('Word', WordSchema);

在猫鼬中创建新文档时如何添加新属性?像这样的东西:

let Word = require("../models/word");
let initWord = "hello";
word = new Word({
   word: initWord,
   length: initWord.length
});

word.save(function(error) {
  if (error) {  
    //some code              
  } else {
    //some code              
  }
});

但这不起作用

1 个答案:

答案 0 :(得分:2)

默认情况下,Mongoose不允许您向文档中动态添加字段。但是,如果使用strict选项设置为false来创建模式,则可以:

var WordSchema = new Schema({
word: {
    type: String
}
}, {strict: false});

为了获得不在架构中的属性,您需要使用

doc.toObject()

并使用它,或使用

doc.get('length')

在检索到的模式对象上。

相关问题