'冻结'猫鼬子文档

我的安装类似于:

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文档可能会发生更改,当我A使用populate()检索文档时,这些更改将反映在path的对象中b

但是,是否有某种方式可以“冻结b特定A文档的路径就像是:

var id=1;
A.findById(id).populate('b').exec(function(err, a) {
  if (err) return handleErr(err);

  console.log(a.b.x);
  // prints 42

  a.freeze('b') // fictitious freeze() fn
  b.x=20;

  b.save(function(err, b) {
    if (err) return handleErr(err);

    console.log(b.x);
    // prints 20

    A.findById(id).populate('b').exec(function(err, a) {
       if (err) return handleErr(err);

       console.log(a.b.x);
       // 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(a.b.x);
    // prints 42

    a.frozenB = a.b.toJSON(); // Creates new object and assigns it to secondary property

    a.save(function (err, a) {
        b.x=20;

        b.save(function(err, b) {
            if (err) return handleErr(err);

            console.log(b.x);
            // prints 20

            A.findById(id).populate('b').exec(function(err, a) {
                if (err) return handleErr(err);

                console.log(a.frozenB);
                // prints 42

            }); 
        });
    });
});

编辑-如果您需要frozenB完整的猫鼬文档,则只需做同样的事情,但将其设为新文档即可。

// 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(a.b.x);
    // prints 42

    var frozenB = a.b;
    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) {
            b.x=20;

            b.save(function(err, b) {
                if (err) return handleErr(err);

                console.log(b.x);
                // prints 20

                A.findById(id).populate('b').exec(function(err, a) {
                    if (err) return handleErr(err);

                    console.log(a.frozenB);
                    // prints 42

                });
            }); 
        });
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章