“冻结”mongoose子
我有类似的设置:
B.js
var schemaB = new mongoose.Schema({ x: Number, ... }); module.exports = mongoose.model('B', schemaB);
A.js
var schemaA = new mongoose.Schema({ b: {type: mongoose.Schema.Types.ObjectId, ref: 'B'}, ... }); module.exports = mongoose.model('A', schemaA);
有了这个,我的B
文档就可以发生更改,而当我使用populate()检索我的A
文档时,这些更改将反映在pathb
的对象中。
但是,在某个特定的A
文件的pathb
上是否有“ 冻结 ”文件? 就像是:
var id=1; A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(abx); // prints 42 a.freeze('b') // fictitious freeze() fn bx=20; b.save(function(err, b) { if (err) return handleErr(err); console.log(bx); // prints 20 A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(abx); // prints 42 }); }); });
没有语境,我不完全确定你为什么需要。 这个问题似乎应该从更高的层面来看待呢?
我知道的一件事是toJSON函数。 它剥离了Mongoose元数据和逻辑,并留下一个普通的JS对象。 这个对象不会改变,除非你改变它。 然后你可以把这个对象添加到a
与b
不同的属性上。
// A.js var schemaA = new mongoose.Schema({ b: {type: mongoose.Schema.Types.ObjectId, ref: 'B'}, frozenB: {} ... });
// app.js var id=1; A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(abx); // prints 42 a.frozenB = abtoJSON(); // Creates new object and assigns it to secondary property a.save(function (err, a) { bx=20; b.save(function(err, b) { if (err) return handleErr(err); console.log(bx); // prints 20 A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(a.frozenB); // prints 42 }); }); }); });
编辑 – 如果你需要frozenB
作为一个完整的mongoose文件,然后做同样的事情,但使其成为一个新的文件。
// A.js var schemaA = new mongoose.Schema({ b: {type: mongoose.Schema.Types.ObjectId, ref: 'B'}, frozenB: {type: mongoose.Schema.Types.ObjectId, ref: 'B'} ... });
// app.js var id=1; A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(abx); // prints 42 var frozenB = ab; delete frozenB._id; // makes it a new document as far as mongoose is concerned. frozenB.save(function (err, frozenB) { if (err) return handleErr(err); a.frozenB = frozenB; a.save(function (err, a) { bx=20; b.save(function(err, b) { if (err) return handleErr(err); console.log(bx); // prints 20 A.findById(id).populate('b').exec(function(err, a) { if (err) return handleErr(err); console.log(a.frozenB); // prints 42 }); }); }); }); });
- 我应该在Mongoose中逐个返回数组或数据吗?
- MongoDB – 在父文档中填充GridFS文件元数据
- Express.js会话在服务器重新启动时重置
- 在Heroku上为Mongo Labs数据库configurationNode.js连接string
- 使用mongoose时需要明确closures连接吗?
- 在Node.js中,引用同一个文件中的另一个函数会导致“ReferenceError:-function- is not defined”错误
- 防止Node.js中与数据库相关的争用情况
- 从mongodb通过nodejs获取数据并将其转换为html页面
- NodeJS:callback和asynchronous调用