“冻结”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对象。 这个对象不会改变,除非你改变它。 然后你可以把这个对象添加到ab不同的属性上。

 // 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 }); }); }); }); });