所以我按如下方式运行脚本
const db = require("../config/database");
const mongoose = require("mongoose");
const UserSettings = require("../models/userSettings");
const Users = require("../models/users");
// code runs which connects to the db
// assume the models are set up fine and properly linked
Users.create({
userName: account.userName
}, (error, user) => {
if (error) {
console.error(`Could not create user with error: ${user}`);
}
else {
console.log(`User created ${user}`);
}
UserSettings.create({
user: user
}, (error, userSetting) => {
if (error) {
console.error(`UserSettings not created for ${user.userName} : ${error}`);
}
else {
console.log(`settings! ${userSetting}`);
}
});
});
我运行此代码,然后我去我的终端并检查mongo本身,我只有用户集合,而不是usersSetting集合
我很困惑,因为afaik,用户+ userSettings设置方式相同,所以我不确定为什么没有设置userSetting集合:(。
提前致谢!
编辑:这是所要求的2个模式(有点修剪以适应更容易)
Users.js作为我的模特
const mongoose = require("mongoose");
const bcrypt = require("bcrypt-nodejs");
const _ = require("lodash");
const generator = require("../security/generator");
const address = require("./address");
const Schema = mongoose.Schema;
const UsersSchema = new Schema({
userName: {
type: String,
unique: true,
trim: true,
required: true
},
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
required: true,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, "Please fill a valid email address"]
},
password: {
type: String,
required: true
}
});
UsersSchema.methods.isPasswordValid = function(password) {
console.log("Comparing passwords");
return bcrypt.compareSync(password, this.password);
};
UsersSchema.methods.toJSON = function() {
let obj = this.toObject();
delete obj.password;
return obj;
};
UsersSchema.pre("save", function(next) {
let user = this;
console.log("----------");
console.log(user);
if (_.isEmpty(user) || !user.isModified("password")) {
return next();
}
user.password = generator.salt(user.password);
next();
});
const Users = mongoose.model("users", UsersSchema);
module.exports = Users;
来自模特的UserSettings.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSettingsSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users",
required: true,
unique: true
},
useMetricMeasurements: {
type: Boolean,
default: false
},
locale: { //tan: make this a enum
type: String,
default: "en-US"
}
});
UserSettingsSchema.pre("save",function(next){
next();
});
const UserSettings = mongoose.model("userSettings", UserSettingsSchema);
module.exports = UserSettings;
我略微修剪了两个文件,因为我认为其他领域只会分散注意力。
答案 0 :(得分:0)
我相信你的问题是Mongoose是异步的。因此,在调用UserSettings.create()时,可能没有用户持久化。 尝试在
之后立即移动插入代码import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return "Hello Jersey";
}
}