【发布时间】:2020-05-14 21:54:38
【问题描述】:
所以我目前正在尝试替换元素中的数组。
oldEvent.interests = ["test", "test2"];
console.log(oldEvent);
但我的元素在 console.log 中没有改变。 oldEvent.interests 是一个空数组,在日志中它仍然是空的。
我的模型如下所示:
const eventSchema = new mongoose.Schema({
title: {
type: String, required: true, minlength: 2, maxlength: 128,
validate: {
validator: v => /^[\w\d öäüÖÄÜ]*$/.test(v),
message: props => `"${props.value}" may only consist of normal letters and numbers`
},
},
date: {type: Date, required: true},
description: {type: String, required: true, maxlength: 999},
maxParticipants: {type: Number, min: 0},
participants: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}],
joinDeadline: {type: Date, required: true},
interests: {
type: [{type: mongoose.Schema.Types.ObjectId, ref: "Interest"}],
validate: {
validator: v => v.length <= 10,
message: props => `"${props.value}" may only consist of up to 10 interests`
},
},
host: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
location: {type: geoSchema}
});
我不想将数组弹出空然后读取新元素,有没有更优雅的方法?
【问题讨论】:
-
您要在数据库中替换它吗?在这种情况下,您可以使用新数组更新文档。如果要更新 node.js 中的本地值,也可以直接设置。我不确定你的问题是什么,你想在更新之前访问以前的值吗?
-
最终。我有一个稍后运行的函数来检查兴趣字段是否有效,然后我使用 .save 再次保存它。 (还有其他一些验证正在进行,包括猫鼬验证,这就是我要替换数组的原因)但问题是,设置数组,就像在我的示例中一样,不会更改控制台中的
oldEvent.interests-Field .log 它仍然是空的。 -
你可以使用
oldEvent.set({ interest: ["test", "test2"] })和oldEvent.save() -
正是我想要的,我不知道为什么
=不起作用。如果你愿意,你可以为那个回答;:) -
编辑:set 仅在数组为空时有效,我可以设置一次,但 set 也不会更改数组。 :(
标签: javascript node.js mongoose mongoose-schema