【发布时间】:2018-07-31 08:43:06
【问题描述】:
我的应用程序(mongodb/nodejs)有问题,我的目标是保存一个集合:
const Job = require("../models/Job");
exports.saveJob = (req, res, next) => {
const newJob = new Job(req.body);
newJob.gender = 'Male';
newJob.save((err, myjob) => {
myjob.code = '1234';
myjob.save((err, mysavedjob) => {
console.log(mysavedjob);
/** OUTPUT **
* { __v: 0,
updatedAt: 2018-07-31T08:31:47.664Z,
createdAt: 2018-07-31T08:31:47.664Z,
gender:'Male',
code:'1234',
...
}
*/
})
})
}
如您所见,代码输出了保存的文档,但是当我检查数据库时,我没有代码:'1234' 我只有
{ __v: 0,
updatedAt: 2018-07-31T08:31:47.664Z,
createdAt: 2018-07-31T08:31:47.664Z,
gender:'Male',
...
}
==== 更新(添加 JobModel)====
const mongoose = require("mongoose");
const JobSchema = new mongoose.Schema(
{
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
code: String,
gender: String,
},
{ timestamps: true }
);
module.exports = mongoose.model("Job", JobSchema, "jobs");
有人可以告诉我为什么吗? 谢谢。
【问题讨论】:
-
工作模型可以共享吗?
-
嘿,谢谢,我刚刚更新了帖子。
-
您的代码按预期工作。我已经创建了您的代码的独立版本,也许这会对您有所帮助github.com/peterjgrainger/mongoose-sandbox。我不确定您如何处理连接或如何检查数据库或您已经拥有的数据,所以这可能是一个因素?
-
要运行它,您需要停止运行 mongo 的任何本地副本,然后是
docker-compose up -d然后是node app.js -
您发布的代码没有任何问题,我自己在本地运行,一切都很好:) 检查了数据库中的所有内容,包括代码
标签: node.js mongodb collections