#node.js #mongodb #mongoose #mongodb-query
Вопрос:
Вот объект, который я отправляю в 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);
Курсы, которые возвращаются как объект сверху
Комментарии:
1. Взгляните на функцию .ToObject mongoosejs.com/docs/api/…
2. Можете ли вы сказать, как вы сохраняете и извлекаете данные из базы данных (ваш фактический код)?
3. Привет, ребята, большое спасибо за быстрый ответ, я обновил свой вопрос, чтобы показать код, который я использовал для создания нового объекта базы данных
Ответ №1:
При вызове new Course
вы создаете модель мангуста, которая также возвращается после вызова course.save
, чтобы получить только данные, попробуйте использовать toObject
метод Course
модели
// 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());