【问题标题】:How do I retrieve only the raw data stored on my mongo database?如何仅检索存储在 mongodb 数据库中的原始数据?
【发布时间】:2021-09-23 02:58:37
【问题描述】:

这是我发布到 mongoDb 并且在 Mongo Compass 中可见的对象

        name: "Angular Course",
        author: "Mosh",
        tags: ["angular", "frontend"],
        isPublished: true,
    });

当我使用 .save() 方法成功发布它时。返回的对象要复杂得多。 当我尝试获取数据库时,我也以相同的方式接收数据。

  '$__': InternalCache {
    strictMode: true,
    selected: undefined,
    shardval: undefined,
    saveError: undefined,
    validationError: undefined,
    adhocPaths: undefined,
    removing: undefined,
    inserting: true,
    version: undefined,
    getters: {},
    _id: 60ee787103000551d4f4fc6c,
    populate: undefined,
    populated: undefined,
    wasPopulated: false,
    scope: undefined,
    activePaths: StateMachine {
      paths: {},
      states: [Object],
      stateNames: [Array],
      forEach: [Function],
      map: [Function]
    },
    pathsToScopes: {},
    ownerDocument: undefined,
    fullPath: undefined,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: 0,
      [Symbol(kCapture)]: false
    },
    '$options': true
  },
  isNew: false,
  errors: undefined,
  _doc: {
    tags: [
      'angular',
      'frontend',
      toBSON: [Function: toBSON],
      _atomics: {},
      _parent: [Circular],
      _cast: [Function: _cast],
      _markModified: [Function: _markModified],
      _registerAtomic: [Function: _registerAtomic],
      '$__getAtomics': [Function: $__getAtomics],
      hasAtomics: [Function: hasAtomics],
      _mapCast: [Function: _mapCast],
      push: [Function: push],
      nonAtomicPush: [Function: nonAtomicPush],
      '$pop': [Function: $pop],
      pop: [Function: pop],
      '$shift': [Function: $shift],
      shift: [Function: shift],
      pull: [Function: pull],
      splice: [Function: splice],
      unshift: [Function: unshift],
      sort: [Function: sort],
      addToSet: [Function: addToSet],
      set: [Function: set],
      toObject: [Function: toObject],
      inspect: [Function: inspect],
      indexOf: [Function: indexOf],
      remove: [Function: pull],
      _path: 'tags',
      isMongooseArray: true,
      validators: [],
      _schema: [SchemaArray]
    ],
    date: 2021-07-14T05:38:57.964Z,
    _id: 60ee787103000551d4f4fc6c,
    name: 'Angular Course',
    author: 'Mosh',
    isPublished: true,
}

我希望它只返回带有类参数的对象。有没有办法我可以用更简单的方式做到这一点?任何帮助将不胜感激!

这是我用来创建新数据库对象的代码

    .connect("mongodb://localhost:27017/playground")
    .then(() => console.log("connected to mongodb"))
    .catch((err) => console.error("couldnt not connect to mongodb:", err));

//this schema defines the shape of course documents on our Mongodb database
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    tags: [String],
    date: { type: Date, default: Date.now },
    isPublished: Boolean,
});

// compile the schema into a model to create a class

//model method takes 2 arguments
//singular name of the collection that this model is for
//schema that defines the shape of documents in this collection
//this returns a class and the class is named with Pascal naming convention
const Course = mongoose.model("Course", courseSchema);

//any asyncronous functionality must be run inside an async function
async function createCourse() {
    // creating an object based on that class
    const course = new Course({
        name: "Angular Course",
        author: "Mosh",
        tags: ["angular", "frontend"],
        isPublished: true,
    });

    // this method is an asyncronous method
    const result = await course.save();
    console.log(result);

从上面作为对象返回的课程

【问题讨论】:

  • 看看.toObject函数mongoosejs.com/docs/api/…
  • 您能说出您是如何从数据库中保存和检索的(您的实际代码)吗?
  • 大家好,非常感谢您的快速回复,我更新了我的问题以显示我用来创建新数据库对象的代码

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

当您调用new Course 时,您会创建一个猫鼬模型,在您调用course.save 后也会返回该模型,以便仅获取数据尝试使用Course 模型的toObject 方法

// creating an object based on that class
const course = new Course({
    name: "Angular Course",
    author: "Mosh",
    tags: ["angular", "frontend"],
    isPublished: true,
});

// this method is an asyncronous method
const result = await course.save();
console.log(result.toObject());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-10
    • 2011-08-19
    • 1970-01-01
    • 2019-12-03
    • 2020-07-23
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    相关资源
    最近更新 更多