猫鼬.save()不起作用
问题描述:
我正在运行那些代码,尝试将 保存对象 到 MongoDB 中.
I have those code running try to save an object into MongoDB.
.save()
从未成功运行.代码运行良好.
The .save()
never got success run. the code running fine.
.save()
方法不起作用.
var conn = mongoose.createConnection(mongoUrl, {auth: {authdb: "admin"}});
conn.on('error', function (err) {
throw err;
});
conn.once('open', function callback() {
console.log("connected to " + mongoUrl);
var cacheSchema = mongoose.Schema({}, {strict: false});
cacheSchema.set('collection', 'caches');
// you need to specify which connection is uing.
var Cache = conn.model('cache', cacheSchema);
var measure = new Cache();
measure['test'] = "test";
measure.save(function(err){
console.log('test');
});
});
答
我刚刚在我的代码中遇到了类似的问题.对于我来说,我正在处理用户文档中的一个对象.我必须在user.save()
之前运行user.markModified('object')
,以确保所做的更改已保存到数据库中.
我的理论是猫鼬不会自动跟踪未设置或从数据库中删除的项目
I just ran into a similar issue in my code. For mine, I was dealing with an object within my user document. I had to run a user.markModified('object')
before the user.save()
to ensure the changes were saved to the database.
My running theory is that Mongoose wasn't tracking items unset or removed from the database automatically