我在 Mongoose 中的 $push 方法不起作用 [英] My $push method in Mongoose does not work ok
问题描述
我在理解为什么 $push 只在嵌套数组中创建一个元素并只显示该元素的 id 时遇到问题
I have a problem understanding why $push creates only one element in nested array and shows only the id of that element
const mongoose = require('mongoose');
let historySchema = new mongoose.Schema({
time: {
type:String
}
})
//users schema
let userSchema = new mongoose.Schema({
name:{
type:String,
},
dob:{
type:String,
},
email:{
type:String,
},
noOfpeopleClimbing:{
type: Number,
default:0
},
details:{
type:String,
},
status:{
type: Boolean,
default: false
},
timeIn:{
type: Number,
default: 0
},
timeOut:{
type: Number,
default: 0
},
timeFinal:{
type: Number,
default: 0
},
timeHistory:[{historySchema}]
})
let User = module.exports = mongoose.model("User", userSchema);
我说的是 timeHistory:[{historySchema}] 其余的你可以忽略.我正在运行下一个测试:
I am talking about timeHistory:[{historySchema}] the rest you can ignore. I am running the next test:
app.post('/users/reset_timeIn/:id', function(req,res){
Users.findOneAndUpdate({_id:req.params.id},{
timeIn:0,
timeOut:0,
timeFinal:0,
timeHistory:{
$push: {time:"some text" }
},
status:false,
noOfpeopleClimbing:0
},function(err){
if(err){
console.log(err);
return
}else{
res.redirect(req.get('referer'));
}
})
});
时间:一些文本"仅用于测试.这次测试的输出,不管推了多少次elment都是这样的:
time:"some text"is just for testing. The output of this test, no matter how many times I have pushed an elment is like this:
{
"noOfpeopleClimbing": 0,
"status": false,
"timeIn": 0,
"timeOut": 0,
"timeFinal": 0,
"_id": "5fa3faa68b302530fcb6bba5",
"name": "Name",
"dob": "1666-02-02",
"email": "name@name.com",
"__v": 0,
"details": "name",
"timeHistory": [
{
"_id": "5fa44343aece7d37dc532fd9"
}
]
},
时间历史"应该包含 id 和字段时间:一些文本",对吗?如果我推送另一条记录以在该数组的第二个对象中包含该记录?正确的?请帮忙
The "timeHistory" should containt the id and the field time:"some text", right? And if i push another record to have that one as in the second object of that array? right? Please help
推荐答案
看起来您没有使用 $push
正确.尝试将正确的路径传递给操作员,在您的情况下是:
Looks like you're not using $push
correctly. Try passing the correct path to the operator, which in your case is:
Users.findByIdAndUpdate(req.params.id, {
timeHistory: {
$push: {
time: "some text"
}
}
})
以下是 mongoplayground 的示例.
这篇关于我在 Mongoose 中的 $push 方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!