猫鼬数组推送并没有保存我的条目,也违背了我使用推送的简单愿望



我有两个模式:

var optionsSchema = new Schema({
locationname: String,
locationnumber : String     
});
var Xoption = mongoose.model('Xoption', optionsSchema);
var estoreSchema = new Schema({
user: String,
odds: String,
//options: [optionsSchema]
options: [{ type: Schema.Types.ObjectId, ref: 'Xoption' }]
});
var Estore = mongoose.model('Estore', estoreSchema);

export default Estore;
export {  Xoption };

请注意,这些选项具有[{type:Schema.Types.ObjectId,ref:'Xoption'}],因此它将存储xoptions集合中对象的ID。

以下是一个Estore文档的示例:

{
"_id" : ObjectId("5f998198df1e7b7598ba307c"),
"options" : [
ObjectId("5f998198df1e7b7598ba307b")
],
"user" : "two",
"odds" : "two",
"__v" : 0
}

正如您所看到的,options数组包含Xoptions集合的id。现在,当我尝试将另一个id推送到选项数组时,我会执行以下操作:我从Xoption模型中获取id。为了简化这里的代码并放大问题的相关部分,我只将其分配给一个变量:

let getid = 'ObjectId("5f997d78ace0547ba8c05646")';   

现在我需要将该id推送到我的Estore中的选项数组,所以我做了以下操作:

Estore.findOne({ "odds": "two" }).then(doc => {
console.log("xxx", doc.options);
doc.options.push(getid);
}).catch(err => {
console.log("error message :", err);
});

当我这样做时,我会得到一个错误:错误转换为ObjectId,错误原因是:

reason:
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

现在我有了进展,所以我从变量中取出了ObjectId,我没有得到错误,但id没有推送到选项数组:

let getid = '5f997d78ace0547ba8c05646';

这只是一个练习代码。复制,更改,再给我发一个例子。帮助我理解为什么对数组进行简单的推送操作不起作用。

我的问题是:如何将该变量的值推送到选项数组?

问题是在我更新模型后保存它。因此:

Estore.findOne({ "odds": "two" }).then(doc => {
console.log("xxx", doc.options);
doc.options.push(getid);
}).catch(err => {
console.log("error message :", err);
});

只需在push((后添加save:

doc.save()

完整的代码应该是:

Estore.findOne({ "odds": "two" }).then(doc => {
console.log("xxx", doc.options);
doc.options.push(getid);
doc.save();
}).catch(err => {
console.log("error message :", err);
});

此外,选项:[{type:Schema.Types.ObjectId,ref:'Xoption'}]接受具有24位字符的ObjectId,您以前不需要ObjectId,它应该是这样的:

let getid = '5f997d78ace0547ba8c05646';

最新更新