[英]mongodb mongoose nodejs express4 why insert a _id in Object Array field automatically?
It might be conceptual question about _id
in mongodb. 在mongodb中,这可能是关于
_id
概念性问题。
I understand mongodb will insert a _id
field automatically if you don't set key field in document.In my case, I defined a field as Object Array, I don't know why it always create a _id
in each Object in Array of this field. 我知道如果您没有在文档中设置键字段,mongodb会自动插入一个
_id
字段。在我的情况下,我将一个字段定义为对象数组,我不知道为什么它总是在此数组的每个对象中创建一个_id
领域。
I do appreciate if someone could clarify it for me. 如果有人可以为我澄清,我非常感谢。
Mongoose Model Scheme definition: 猫鼬模型计划的定义:
module.exports = mongoose.model("Application", {
Name: String,
Description: String,
Dependency: [
{
App_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Application'
},
Priority: Number
}
]
});
This is an Update operation, request data is: 这是一个更新操作,请求数据为:
{ _id: '571953e33f33c919d03381b5',
Name: 'A Test Utility (cmd)',
Description: 'A Test Utility (cmd)'
Dependency:
[ { App_id: '571953e33f33c919d03381b6', Priority: true },
{ App_id: '571953e33f33c919d03383da', Priority: 0 } ]
}
I use this code to update it 我用这段代码来更新它
var id = req.body._id;
Application.findOneAndUpdate({ _id: id }, req.body, function (err, app) {
if (err)
res.send(err);
res.json(app);
});
The update is successful.But the document in mongodb is: 更新成功。但是mongodb中的文档是:
{
"_id" : ObjectId("571953e33f33c919d03381b5"),
"Name" : "A Test Utility (cmd)",
"Description" : "A Test Utility (cmd)",
"Dependency" : [
{
"Priority" : 1,
"App_id" : ObjectId("571953e33f33c919d03381b6"),
"_id" : ObjectId("571a7f552985372426509acb")
},
{
"Priority" : 0,
"App_id" : ObjectId("571953e33f33c919d03383da"),
"_id" : ObjectId("571a7f552985372426509aca")
}
]
}
I just don't understand how come the _id
in the "Dependency" Array? 我只是不明白
_id
在“ Dependency”数组中的位置如何?
Thanks. 谢谢。
When you use [{..}]
that means inside it act as a sub schema and you know that MongoDB insert a _id
field automatically if you don't set key field in document. 当您使用
[{..}]
,意味着它在内部充当子架构,并且您知道,如果未在文档中设置键字段,MongoDB会自动插入_id
字段。 So you need to force to insert document without _id
field. 因此,您需要强制插入没有
_id
字段的文档。
Need use {_id:false}
for your Dependency array schema to insert without _id
需要对您的Dependency数组架构使用
{_id:false}
来插入而不使用_id
var ApplicationSchema = new mongoose.Schema({
Name: String,
Description: String,
Dependency: [
{
App_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Application'
},
Priority: Number,
_id: false
}
]
});
module.exports = mongoose.model("Application", ApplicationSchema);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.