我在尝试为单个文档设置虚拟时遇到问题。基本上我试图让我的文档保留我实际上并不想保存在数据库中的值。这是示例代码。
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const bookSchema = new Schema({
title: String,
}, {
toObject: { virtuals: true },
toJSON: { virtuals: false }
})
bookSchema.virtual('desc').get(() => {
return this.__desc
}).set((val) => {
this.__desc = val
})
const bookModel = mongoose.model('book', bookSchema)
let first_book = new bookModel()
first_book.title = "desc should be first"
first_book.desc = "first"
console.log("FIRST BOOK", first_book,"\n","\n")
let second_book = new bookModel()
second_book.title = "desc should be second"
second_book.desc = "second"
console.log("FIRST BOOK AGAIN", first_book)
当我输出first_book
时,我按预期得到desc: 'first'
。但是,当我在设置second_book.desc = "second"
后输出它时,由于某种原因,desc
的{{1}}虚拟内容已更改。我似乎无法找到有关虚拟范围的任何文档,但我希望first_book
保留first_book.desc
。
我这样做错了吗?是否有另一种方法可以使文档保留在不属于数据库的数据中?