gpt4 book ai didi

node.js - 在 Mongoose 中创建新文档时可以添加新属性吗?

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:48 25 4
gpt4 key购买 nike

我有这个架构(例如):

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

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

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
}
});

但这不起作用

最佳答案

默认情况下,Mongoose 不允许您向文档动态添加字段。

但是,如果您创建架构时将 strict 选项设置为 false,则可以:

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

为了获取不在架构中的属性,您需要使用特殊的 getter 形式:

doc.get('length')

或者通过调用将文档转换为普通的旧 JavaScript 对象:

doc.toObject()

在检索到的架构对象上。

关于node.js - 在 Mongoose 中创建新文档时可以添加新属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com