本文介绍了es6传播算子-猫鼬结果副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongo DB和mongoose开发一个快速的js API.

我想在Javascript es6中创建一个由少量变量和猫鼬请求的结果组成的对象,并希望通过es6传播运算符来实现:

MyModel.findOne({_id: id}, (error, result) => {
   if (!error) {
      const newObject = {...result, toto: "toto"};
   }
});

问题在于,将扩展运算符应用于结果会以一种怪异的方式对其进行转换:

newObject: {
   $__: {
      $options: true,
      activePaths: {...},
      emitter: {...},
      getters: {...},
      ...
      _id: "edh5684dezd..."
   }
   $init: true,
   isNew: false,
   toto: "toto",
   _doc: {
      _id: "edh5684dezd...",
      oneFieldOfMyModel: "tata",
      anotherFieldOfMyModel: 42,
      ...
   }
}

我有点明白猫鼬会丰富对象的结果以允许与之进行特定的交互,但是当我在执行console.log之前,它描绘了一个没有所有这些东西的简单对象.

我不想通过做 ... result._doc 来作弊,因为我将这一部分抽象化了,它不适合这种方式.也许有一种方法可以复制没有外来东西的对象.

谢谢您的时间.

解决方案

您可以使用Mongoose Document.toObject()方法.它将返回从数据库中获取的底层普通JavaScript对象.

const newObject = {...result.toObject(), toto: "toto"};

您可以在此处了解更多有关.toObject()方法的信息.. >

I'm developping an express js API with mongo DB and mongoose.

I would like to create an object in Javascript es6 composed of few variables and the result of a mongoose request and want to do so with es6 spread operator :

MyModel.findOne({_id: id}, (error, result) => {
   if (!error) {
      const newObject = {...result, toto: "toto"};
   }
});

The problem is that applying a spread operator to result transform it in a wierd way:

newObject: {
   $__: {
      $options: true,
      activePaths: {...},
      emitter: {...},
      getters: {...},
      ...
      _id: "edh5684dezd..."
   }
   $init: true,
   isNew: false,
   toto: "toto",
   _doc: {
      _id: "edh5684dezd...",
      oneFieldOfMyModel: "tata",
      anotherFieldOfMyModel: 42,
      ...
   }
}

I kind of understand that the object result is enriched by mongoose to permit specific interactions with it but when I console.log before doing so it depict a simple object without all those things.

I would like not to cheat by doing ...result._doc because I abstract this part and it won't fit that way. Maybe there is a way to copy an object without eriched stuff.

Thank you for your time.

解决方案

You can use the Mongoose Document.toObject() method. It will return the underlying plain JavaScript object fetched from the database.

const newObject = {...result.toObject(), toto: "toto"};

You can read more about the .toObject() method here.

这篇关于es6传播算子-猫鼬结果副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:44