英文:
What is the right way to store an array of objects in MongoDB using Mongoose?
问题
- 创建另一个子模式
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);
- 创建嵌套对象
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.
- 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);
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论