最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用 Mongoose 在 MongoDB 中存储对象数组的正确方法是什么?

网站源码admin31浏览0评论

使用 Mongoose 在 MongoDB 中存储对象数组的正确方法是什么?

使用 Mongoose 在 MongoDB 中存储对象数组的正确方法是什么?

语言:Javascript,环境:Node JS,框架:Express & 库:Mongoose

我正在开发一个应用程序,我需要将一些数据以对象数组的形式存储在 mongoDB 文档中?

我在网上搜索了一下,有两种不同的方法。

  1. 创建另一个子模式
const mongoose = require('mongoose');
const subSchema = new mongoose.Schema({
    name: String,
    age: Number
});

const schema = new mongoose.Schema({
    details: [subSchema]
});

const model = mongoose.model('Model', schema);
  1. 创建嵌套对象
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
    details: [{
        name: String,
        age: Number
    }]
});

现在,哪一个是正确的方法,应该使用?另外,这有什么隐藏的字符串吗?

附:

我正在使用第二种方法,在存储数据时,

details
中的每个对象都有一个单独的 ObjectID。这就是区别吗?

回答如下:
发布评论

评论列表(0)

  1. 暂无评论