假设我想创建一个具有嵌套属性的用户架构:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
/* ... some other properties ... */
profile: {
firstName: { type: String, default: '' },
/* ... some other properties ... */
},
});
module.exports = mongoose.model('User', userSchema);
现在,如果我想在像 ExpressJs 这样的 Nodejs 框架中保存用户,我会像这样保存它:
var user = new User({
username: req.body.username,
profile.firstName: req.body.firstName /* this is what i want to achive here */
});
user.save(function(err) {
if (!err) {
console.log('User created');
}
});
我想知道我的架构是否良好,或者最好的做法是在根中创建所有属性,如下所示:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
firstName: { type: String },
/* ... some other properties ... */
},
});
最佳答案
您的架构很好,但您无法像在第二个代码示例中那样在新对象的根上定义嵌套属性而不引用它们。它应该看起来像这样:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = mongoose.model('User', {
username: String,
profile: {
firstName: String
}
});
var user1 = new User(
{
username: 'Zildjian',
'profile.firstName':'test'
});
user1.save(function (err) {
if (err) // ...
console.log('meow');
process.exit(0);
});
尽管我建议像这样正确嵌套它
var user1 = new User(
{
username: 'Zildjian',
profile: {
firstName:'test'
}
});
关于javascript - 如何使用 mongoose 保存嵌套的 mongoDB 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406012/