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

huangapple go评论65阅读模式
英文:

What is the right way to store an array of objects in MongoDB using Mongoose?

问题

  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
    }]
});

关于哪种方法是正确的,应该使用哪种,以及是否有潜在问题,我无法回答。

英文:

Language: Javascript, Environment: Node JS, Framework: Express & Library: Mongoose

I was working on an application where I needed to store some data in a mongoDB document in the form of an array of objects?

There are two different ways to do this once I searched the internet.

  1. Create another sub-schema
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. Create a nested object
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
    details: [{
        name: String,
        age: Number
    }]
});

Now, which one is the right method and should be used? Also, are there any hidden strings to this?

PS:

I am using the second method and while storing the data, each object inside details is having a separate ObjectID with it. Is this the difference?

答案1

得分: 0

我找到了 mongoose 的一个有用解释:

https://mongoosejs.com/docs/subdocs.html#subdocuments-versus-nested-paths

英文:

Because your question is what are the differences between the two approaches, I found a helpful explanation by mongoose:

https://mongoosejs.com/docs/subdocs.html#subdocuments-versus-nested-paths

huangapple
  • 本文由 发表于 2023年5月7日 18:12:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定