QUITE _id массива при отправке сообщения на mongoose - PullRequest
1 голос
/ 13 января 2020

Мне нужна помощь для создания БД с этой моделью. (это для api mon goose и express, я могу использовать схему mongoshell или mon goose).

{
"hotels" : [{
"name" : "Hotel Emperador",
"stars" : "3",
"images" :[....],
"price" : "1596",
},
...]
}

, но когда я отправляю массив в MongoDB, автоматически создаю _id:"" для моего массив, я могу удалить это? Мне нужно _id, но для моих документов внутри массива я получаю что-то вроде этого:

{"_id": "5e181fed9fc1883a69797e3a", 
  "hotels":[
    {
    "name" : "Hotel Emperador",
    "stars" : 4,
    "price" : 1596,
    "imagen" : "https://i.ibb.co.jpg",
    "id": 1
    },...]}

Мне нужно что-то подобное, потому что это очень сложно для меня. найти документы с предыдущим кодом.

{
"hoteles": [
    {
        "_id": "5e1217b81c9d440000632fd7",
        "nombre": "Hotel Sonesta",
        "direccion": "Cerritos",
        "telefono": "3152020",
        "estrellas": "5",
        "precio": "850000",
        "imagenes": "https://i.ibb.co/t2Hc8c4/Hotel-Sonesta.jpg"
    },
    {
        "_id": "5e1218211c9d440000632fd8",
        "nombre": "Hotel Soratama",
        "direccion": "Centro",
        "telefono": "3204545",
        "estrellas": "4",
        "precio": "540000",
        "imagenes": "https://i.ibb.co/vcyqQSf/Soratama.jpg"
    },..]}

Я знаю, что схема модели может быть полезной, но попробовала и не сработала Можете ли вы помочь мне?

Ответы [ 2 ]

0 голосов
/ 13 января 2020

Ваша модель должна быть такой:

Модель:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var hotelSchema = new Schema({
    _id: false, //remove this line , it will automatic generate the _id for document which is not harmfull for you case
    hoteles: [{
        _id : true, // even if we do not mention the key _id , it will auto generate the unique _id for every object in the array of hotels
        nombre: {type : String} ,
        direccion: {type : String},
        telefono: {type : String}, 
        estrellas: {type : String},
        precio: {type : String}, 
        imagenes: {type : String}, 
    }],

});


module.exports = mongoose.model('hotel' , hotelSchema);  

Попробуйте этот код

0 голосов
/ 13 января 2020

Ваша схема должна быть такой:

 // Option : 1
 const hotelesSchema = new Schema({
    "_id" : Number, // This is optional now
    "nombre": String,
    "direccion": String,
    "telefono": String,
    "estrellas": String,
    "precio": String,
    "imagenes": String
}) 

 /** Option : 2

(Or if you don't even need it at all -> _id will not be created automatically or even if you pass it won't be inserted)

const hotelesSchema = new Schema({
    "nombre": String,
    "direccion": String,
    "telefono": String,
    "estrellas": String,
    "precio": String,
    "imagenes": String
}, { _id: false }) */


const mainSchema = new Schema({
    hoteles: [ hotelesSchema ]
}, { _id: false }); // Adding { _id: false } will not create _id on top level.

const MainColModel = mongoose.model('yourActualCollectionName', mainSchema, 'yourActualCollectionName');

Код:

const mainColObj = new MainColModel({
            hoteles: [{
                "_id": 123, // If you don't pass it here it won't be created.
                "nombre": "Hotel Sonesta",
                "direccion": "Cerritos",
                "telefono": "3152020",
                "estrellas": "5",
                "precio": "850000",
                "imagenes": "https://i.ibb.co/t2Hc8c4/Hotel-Sonesta.jpg"
            },
            {
                "_id": 456,
                "nombre": "Hotel Soratama",
                "direccion": "Centro",
                "telefono": "3204545",
                "estrellas": "4",
                "precio": "540000",
                "imagenes": "https://i.ibb.co/vcyqQSf/Soratama.jpg"
            }]
        })

let dbResp = await mainColObj.save();

Результат:

{
    "_id" : ObjectId("5e1bee2a39ae20e06dc116db"), // Won't be created if you add , { _id: false } to mainSchema
    "hoteles" : [ 
        {
            "_id" : 123, // You don't see _id in Option : 2
            "nombre" : "Hotel Sonesta",
            "direccion" : "Cerritos",
            "telefono" : "3152020",
            "estrellas" : "5",
            "precio" : "850000",
            "imagenes" : "https://i.ibb.co/t2Hc8c4/Hotel-Sonesta.jpg"
        }, 
        {
            "_id" : 456, // You don't see _id in Option : 2
            "nombre" : "Hotel Soratama",
            "direccion" : "Centro",
            "telefono" : "3204545",
            "estrellas" : "4",
            "precio" : "540000",
            "imagenes" : "https://i.ibb.co/vcyqQSf/Soratama.jpg"
        }
    ],
    "__v" : 0
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...