Node.js 在mongoose中更新但不保存文档
我一直在努力想办法解决这个问题。我的文档显示它正在更新,但没有保存到数据库。基本上,当我保存模块文档时,我希望层文档被更新(正在工作),层id也被添加到当前模块文档中(它显示更新,但不保存到db) 我的模式Node.js 在mongoose中更新但不保存文档,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我一直在努力想办法解决这个问题。我的文档显示它正在更新,但没有保存到数据库。基本上,当我保存模块文档时,我希望层文档被更新(正在工作),层id也被添加到当前模块文档中(它显示更新,但不保存到db) 我的模式 var moduleSchema = new Schema({ title: { type: String, unique: true }, description: String, tier: [{ type:
var moduleSchema = new Schema({
title: {
type: String,
unique: true
},
description: String,
tier: [{
type: Schema.Types.ObjectId,
ref: 'Tier'
}]
})
我的自定义实例方法
moduleSchema.methods.saveInTier = function(tierTitles, cb){
// expects an array of tier names
var self = this;
var updateTier = function(i){
Tier.findOneAndUpdate({title: tierTitles[i]},
{$addToSet: {modules: self._id}},
function(err, tier){
if(err) throw err;
//self.tier.set(i, tier._id)
self.tier.addToSet(tier._id)
console.log("module saved in tier: ", tier.title)
return self.tier
})
}
for(var j=0;j<tierTitles.length;j++){
updateTier(j)
}
}
访问数据库
Module.find({}, function(err, docs){
console.log(docs) // the tier field is not updated in the database
})
mongodb文档说,“$addToSet操作符向数组添加一个值,除非该值已经存在,在这种情况下,$addToSet对该数组不做任何操作。”因此,如果层已经存在,则不会更新。是的,我知道这一点。数组一开始是空的。它显示它已更新,但当我检查数据库时,它只显示一个空数组,其中保存的ID mongodb文档说,“除非该值已经存在,否则$addToSet运算符会向数组中添加一个值,在这种情况下,$addToSet不会对该数组进行任何操作。”因此,如果层已经存在,则不会更新层。是的,我知道这一点。数组一开始是空的。它显示它已更新,但当我检查数据库时,它只显示一个空数组,其中保存了ID
Module.find({}, function(err, docs){
console.log(docs) // the tier field is not updated in the database
})