是否有任何特殊原因或情况无法向猫鼬架构添加新字段?



我现在正迈出作为后端开发者的第一步。

它是用Node.js, Serverless, MongoDB构建的,采用微服务设计模式。

我遇到了一个问题,我认为很简单,我以前做过很多次:向Mongoose Schema添加一个字段。

原Schema:

const collectionName = "A";
const CollectionSchema: mongoose.Schema = new mongoose.Schema({
AType: String,
userId: String,
origin: String,
timestamp: Date,
value: Number,
context: String,
sport: {
matchId: String,
teamId: String,
actionId: String,
matchTime: String,
followedTeam: String,
},
pro: {
eventId: String,
subjectId: String,
},
comment: String,
orgs: [String],
sex: String,
birthDate: String,
test: {
type: String,
default: "TEST"
}
});

与我要添加的字段相同:

const collectionName = "A";
const CollectionSchema: mongoose.Schema = new mongoose.Schema({
AType: String,
userId: String,
origin: String,
timestamp: Date,
value: Number,
context: String,
newElementId: String, **//<------- new field**
sport: {
matchId: String,
teamId: String,
actionId: String,
matchTime: String,
followedTeam: String,
},
pro: {
eventId: String,
subjectId: String,
},
comment: String,
orgs: [String],
sex: String,
birthDate: String,
test: {
type: String,
default: "TEST"
}
});

在点击lambda之后,然后是:

try {
MyCollection = mongoose.model(collectionName);
} catch (e) {
MyCollection = mongoose.model(collectionName, CollectionSchema);
}

export async function postMyAction(content: MyInterface): Promise<string> {
console.log('Content => ', content); **// <---- new field appears**
try {
await db.connect();
const value = await MyCollection.create(content);

console.log('Returned value after creation => ', value); **// <---- new field does not appear**

return value._id;
} catch (err) {
console.log(err);
}
}

故障排除:

如果您注意控制台日志,

-新字段实际上被添加到模式中,因为它出现在我发送给Mongo的内容中。

-虽然,它不会在之后的返回值中显示。

虽然这个对象是在mongoDB中创建的,但是没有添加新的字段。

所有的微服务都是用相同的模式构建的,这在以前从来没有出现过问题。

有什么提示或建议吗?

您应该尝试一下,并根据您的需求进行更改

const mongoose = require('mongoose');
const userSchema =mongoose.Schema({
_id  : mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true},
password        : { type: String, required: true },
friends         :[new mongoose.Schema({
user:{type:String}
},{strict:false})],
profileImage: {type : String, default:"default.jpg"},
userName    :{type :String, required : true},
fullName    :{type: String, required : true},
credits     : {type: Number, default:0},
Tags   :{type : Object,default: null},
backgroundImage : {type:String, default :"default.jpg"},
isDeleted : {type : Boolean , default : false},
deletedAt : {type: Date, default : null},
},{timestamps : true},{strict: false} );
module.exports = mongoose.model('User',userSchema);

最新更新